convert mysql to mysqli [closed]

2019-03-02 13:52发布

问题:

I'm completely new to Mysql and PHP. I wrote a script that works but now realise that I should be using mysqli not mysql. I tried changing all the 'mysql_...' to 'mysqli_' but that didn't work. Can anyone tell me exactly how to rewrite the code below?

 $tableName = "Fixtures";


  //==== CONNECT TO DATABASE
  $con = mysql_connect($host,$user,$pass);
  $dbs = mysql_select_db($databaseName, $con);


  //==== FETCH DATA
  $result = mysql_query("SELECT * FROM $tableName");


  //==== PUT DATA INTO ARRAY
  $array = array();
  while ($row = mysql_fetch_row($result)) {
    $array[] = $row;
  }


  //==== ECHO AS JSON
  echo json_encode($array);

回答1:

It is quite simple

$db = new mysqli("host", "user", "password", "db");
$result = $db->query("SELECT * FROM $tableName");
while ($row = $result->fetch_row()) {
    //etc.
}

I find the php.net documentation on mysqli useful for looking up functions as well as codesnippets. This also answers your question php.net/mysqli_fetch_row