How to convert a MySQL connection to MySQL? [duplicate]

11

I decided to listen to some users to make the conversion but I need your help because I have done a lot of research and nothing works.

The first file is:

<?php 
include_once("/pasta/connectserver.php");
$table = "rjpsync_tag, rjpsync_ipserver";
function assoc_query_2D($sql, $id_name = false){
  $result = mysql_query($sql);
  $arr = array();
  $row = array();
  if($result){
    if($id_name == false){
      while($row = mysql_fetch_assoc($result))
        $arr[] = $row;
    }else{
      while($row = mysql_fetch_assoc($result)){
        $id = $row['id'];
        $arr[$id] = $row;
      }
    }
  }else
      return 0;

  return $arr;
}
function query_whole_table($table, $value = 'ipserver1, ipsserver, ipserverfim'){
    $sql = "SELECT $value FROM $table WHERE idserver = 1";
  return assoc_query_2D($sql);
}
$export_str = "";
$result = query_whole_table($table);
foreach($result as $record){
  $export_str .= implode("",$record);
}
file_put_contents("/pasta/ipserver1.php", $export_str);
?>

And the second file is:

<?php
include_once("/pasta/connectserver.php");
function salvaip() {
$ip = file_get_contents('/pasta/myip.txt','r');
$ip = mysql_escape_string($ip);
$sql = "UPDATE rjpsync_ipserver SET ipsserver='".$ip."' WHERE idserver=1";
if (mysql_query($sql)) {
return true;
}
fclose($ip);
}
salvaip();
?>

These two files are linked to:

# /pasta/connectserver.php
<?PHP
include_once("/pasta/config.php");
$db_host1     = "$s_ipserver1:$db_porta1";
$db_link1     = mysql_connect($db_host1, $db_user1, $db_password1) or die (mysql_error ());
$db_connect1  = mysql_select_db($db_name1, $db_link1);
?>

And I would like to be connected to the following:

# /pasta/connectserveri.php
<?PHP
include_once("/pasta/config.php");
$db_host1     = "$s_ipserver1";
$db_connect1  = mysqli_connect($db_host1, $db_user1, $db_password1, $db_name1, $db_porta1) or die (mysqli_error ());
?>
    
asked by anonymous 17.09.2014 / 13:47

3 answers

1

Sometimes an orientation is worth gold I solved a problem in hours that I have to solve a few weeks ago, once again thank you.

Here are the files changed to work with MYSQLI.

<?php 
include_once("/pasta/connectserver1i.php");
$table = "rjpsync_tag, rjpsync_ipserver";
function assoc_query_2D($sql, $id_name = false){
global $db_connect1;
  $result = mysqli_query($db_connect1, $sql);
  $arr = array();
  $row = array();
  if($result){
    if($id_name == false){
      while($row = mysqli_fetch_assoc($result))
        $arr[] = $row;
    }else{
      while($row = mysqli_fetch_assoc($result)){
        $id = $row['id'];
        $arr[$id] = $row;
      }
    }
  }else
      return 0;

  return $arr;
}
function query_whole_table($table, $value = 'ipserver1, ipsserver, ipserverfim'){
    $sql = "SELECT $value FROM $table WHERE idserver = 1";
  return assoc_query_2D($sql);
}
$export_str = "";
$result = query_whole_table($table);
foreach($result as $record){
  $export_str .= implode("",$record);
}
file_put_contents("/pasta/ipserver1.php", $export_str);
?>

And the second.

<?php
include_once("/pasta/connectserver1i.php");
function salvaip() {
global $db_connect1;
$ip = file_get_contents('/pasta/myip.txt','r');
$ip = mysqli_escape_string($db_connect1, $ip);
$sql = "UPDATE rjpsync_ipserver SET ipsserver='".$ip."' WHERE idserver=1";
if (mysqli_query($db_connect1, $sql)) {
return true;
}
fclose($ip);
}
salvaip();
?>
    
17.09.2014 / 22:01
6

To migrate a code that uses the mysql_ * functions to mysqli, some changes are required such as adding new parameters or changing their order in the function calls and also using the available resources such as prepared statements and transaction control.

list_legado.php

$link = mysql_connect('host', 'usuario', 'senha');
mysql_select_db('banco');
$sql = 'SELECT * FROM tabela';
$result = mysql_query($sql) or die(mysql_error());

while($item = mysql_fetch_assoc($result)){
    echo $item['campo1'] .'-'. $item['campo2'] .'<br>';
} 

listar_novo.php

$link = mysqli_connect('host', 'usuario', 'senha', 'banco');
//mysqli_select_db($link, 'test'); //Alternativa para selecionar/trocar o banco...
$sql = 'SELECT * FROM tabela';
$result = mysqli_query($link, $sql) or die(mysqli_error($link));

while($item = mysqli_fetch_assoc($result)){
    echo $item['campo1'] .' - '. $item['campo2'] .'<br>';
}

Listing alternative:

$result = mysqli_fetch_all($result, MYSQLI_ASSOC);

foreach($result as $item){
   echo $item['campo1'] .' - '. $item['campo2'] .'<br>';
}

mysqli_connect () allows you to pass / select the base name as the fourth parameter as well you can do this with the function mysqli_select_db () its use is appropriate when it is necessary to change the database (if it is on the same server) because it is common for a system to access multiple banks.

mysqli_fetch_ * returns only one record while mysqli_fetch_all () returns an array containing all the records at one time, the second parameter indicates the form the data will be accessed ( MYSQLI_NUM numerical array, MYSQLI_ASSOC associative, and MYSQLI_BOTH associative and numerical array. if it is omitted the default will be MYSQLI_NUM .

Insert, update, delete, dynamic queries and prepared statements

Prepared statements avoid sql injection so you do not have to use mysql_real_escape_string for each value of type string and end that sea of single / double quotes.

insert_legado.php

//conexão omitida

$nome = 'nome\'s ); drop table ....';
$id = 1;
$nome = mysql_real_escape_string($nome);

$sql = "INSERT INTO tabela (id, nome) VALUES($id, '$nome')";
mysql_query($sql) or die(mysql_error());

insert_novo.php

//conexão omitida

$sql = 'INSERT INTO tabela (id, nome) VALUES(?,?)';

$stmt =  mysqli_prepare($link, $sql);
$id = 1;
$nome = 'nome\'s ); drop table .... ';
mysqli_stmt_bind_param($stmt, 'is', $id, $nome);

if(!mysqli_stmt_execute($stmt)){
    echo mysqli_error($link);
}

mysqli_prepare () creates a prepared query based on the last string ( $sql ), after that, the '% replacement% placeholders' are replaced by their respective values in mysqli_stmt_bind_param ($ stmt, type, $ vars) where ? is the prepared query, type are the types of each value $stmt = > integers, i = > text fields / varchar etc ... s = > float / double and d = > blob and b are the variables ( $vars ) if no error happens the statement is executed through mysqli_stmt_execute () .

Related:

Select with prepared statements MySQLi

Mysqli bind with an array of values

    
17.09.2014 / 14:11
4

The problem you are experiencing is probably with the function mysql_query .

It had a change in the method signature and you need to pass% dc% of the DB as the first parameter ( documentation ):

mysqli_query ( mysqli $link , string $query )

That is, for all occurrences of link , replace with mysql_query($var)

Using an IDE, it's quite simple to change all of your files from a regular expression's replace:

Search pattern

mysql_query\(($var)\)

Replace with

mysqli_query\(\$db_connect1, $1\)

Example on regexr .

    
17.09.2014 / 14:55