How to adapt code to mysql_

Asked

Viewed 94 times

1

Ola would like to know how I can adapt the code below to mysqli necessarily the excerpt below.

Section to be modified to mysqli

$filmes_generos = array_map('mysql_real_escape_string', array_map('trim', explode("," , $subanime["genero"])));

Connection to the database

$nomeHost = "localhost";
$nomeUsuario = "usuario";
$senhaUsuario = "senha";
$nomeBanco = "banco";
$conecta = mysqli_connect($nomeHost, $nomeUsuario, $senhaUsuario, $nomeBanco) or die("Error " . mysqli_error($conecta));

Complete code

$submedia["genero"] = trim($submedia["genero"], ', ');
$contagem = explode(',', $submedia["genero"]);
$count = count($contagem);
$filmes_generos = array_map('mysql_real_escape_string', array_map('trim', explode("," , $submedia["genero"]))); 
$cont = 1;
foreach ($filmes_generos as $item) {

if ($count == $cont++) { echo $item; } else { echo $item.', '; } 

}

2 answers

2

you can create functions: config

<?php 
   define('DB_HOSTNAME','localhost');
   define('DB_USERNAME','root');
   define('DB_PASSWORD', null);
   define('DB_DATABASE','NomeDaBaseDeDados');
   define('DB_CHARSET','utf8');
?>

connection:

<?php
//Open Conection
function DBConnect(){
    $link = @mysqli_connect(DB_HOSTNAME,DB_USERNAME,DB_PASSWORD,DB_DATABASE) or die(mysqli_connect_error());
    mysqli_set_charset($link, DB_CHARSET) or die(mysqli_error($link));
    return $link;
}

//Close Conection
function DBClose($link){
    @mysqli_close($link) or die(mysqli_error($link));   
}

//Ant-SQL Inject
function DBEscape($dados){
    $link = DBConnect();
    if(!is_array($dados))
        $dados = mysqli_real_escape_string($link, $dados);
    else{
        $arr = $dados;
        foreach ($arr as $key => $value){
            $key   = mysqli_real_escape_string($link, $key);
            $value = mysqli_real_escape_string($link, $value);
            $dados[$key] = $value;
        }
    }
    DBCLOSE($link);
    return $dados;
} ?>

and the cruid for the base date:

<?php
//Create
function DBCreate($table, array $data, $ReturnId = false){
    $table  = $table;
    $data   = DBEscape($data);

    $fields = implode(',', array_keys($data));
    $values = "'".implode("', '", $data)."'";

    $query = "INSERT INTO {$table} ( {$fields} ) VALUES ( {$values})";
    return DBExecute($query, $ReturnId);
}

//Read
function DBRead($table,  $params = null, $fields = "*"){
    $table  = DB_PREFIX . '_' . $table;
    $params = ($params) ? " {$params}" : null;

    $query  = "SELECT {$fields} FROM {$table}{$params}";
    $result = DBExecute($query);

    if(!mysqli_num_rows($result))
        return false;
    else{
        while ($rs = mysqli_fetch_assoc($result)){
            $data[] =$rs;
        }
        return $data;
    }
}

//Update
function DBUpdate($table, array $data, $where = null, $ReturnId = false){
    foreach ($data as $key => $value){
        $fields[] = "{$key} = '{$value}'";
    }
    $fields = implode(', ',$fields);
    $table  = DB_PREFIX . '_' . $table;
    $where = ($where) ? " WHERE {$where}" : null;
    $query  = "UPDATE {$table} SET {$fields}{$where}";

    return DBExecute($query, $ReturnId);
}

//Inject
function DBExecute($query, $ReturnId = false){
    $link   = DBConnect();
    $result = @mysqli_query($link,$query) or die(mysqli_error($link));

    if($ReturnId){
        $result = mysqli_insert_id($link);
    }

    DBClose($link);
    return $result;
}

//Delete
function DBDelete($table, $where = null){
    $table  = DB_PREFIX . '_' . $table;
    $where = ($where) ? " WHERE {$where}": null;
    $query = "DELETE FROM {$table}{$where}";

    return DBExecute($query);
}?>

with your codes would look like this:

$filmes_generos = array_map('mysql_real_escape_string', array_map('trim', explode("," , $subanime["genero"])));

$filmes = array(
    $campos['genero']  =  DBEscape( strip_tags( trim( $subanime['genero'] ) ) 
);

$dbCheak = DBCreate('NomeDaTabela', $filmes);

If($filmes)
   echo 'Done!';
else
   echo 'Faill';

update:

$form['CampoDobanco']   = DBEscape( strip_tags( trim( $_REQUEST['CampoDoForm'] ) ) );
$form['CampoDobanco']   = DBEscape( strip_tags( trim( $_REQUEST['CampoDoForm'] ) ) );
$form['CampoDobanco']   = DBEscape( strip_tags( trim(  $_REQUEST['CampoDoForm'] ) ) );

$Update = DBUpdate('NomeDaTabela',$form ,"WHERE CampoDobanco= '" . $form['CampoDoForm'] . "' and CampoDobanco= '". $form['CampoDoForm']  . "'");

Insert:

DBCreate('TabelaBanco',$form)

delete:

DBDelete('NomeDaTabela',$ArrayDeCampos,'WHERE id = '" . $ArrayDeCampos['Id'] . "'");

works perfectly for me and does not need to be writing querys..

$GerarLista = DBRead('TabelaBanco','order by algumacoisa desc');
if($GerarLista)
foreach ($GerarLista as $ItensDalista):
  $ItensDalista['Indice1'];
  $ItensDalista['Indice2'];
  $ItensDalista['Indice3'];
endforeach;

but if you want to keep your format:

try{
    $db = new PDO("mysql:dbname=NomeDoBanco;host=localhost;charset=utf8;","root","");
    }catch(PDOException $e){
        print $e;
    }

$sqlRead = "SELECT * FROM tabela";
try {
    $read = $db->prepare($sqlRead);
    $read->execute();
} catch (PDOException $e) {
    echo $e->getMessage();
}
while($rs = $read->fetch(PDO::FETCH_OBJ)){
    $rs->campo1
    $rs->campo2
    $rs->campo3 etc...
}
  • Thanks for your help

2


The similar function for mysqli, is the real_escape_string:

$generos_escape = $mysqli->real_escape_string($submedia["genero"]);
$generos = array_map('trim', explode(',', $generos_escape));

Then your connection would be:

$mysqli = new mysqli('localhost', 'usuario', 'senha', 'banco');
  • Grateful for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.