将特定技术从mysql转换为mysqli(php)

将特定技术从mysql转换为mysqli(php)

问题描述:

In mysql I use this code

$somenumber=5;
$result = mysql_query("SELECT * FROM some_table")
while($row = mysql_fetch_array($result)) {
echo $row['id'.$somenumber];
}

Please help me to do the same in the best way using mysqli, probably oop style I think cause everybody say best way to use oop way. Sorry I'm just studding this

在mysql中我使用此代码 p>

  $ somenumber = 5  ; 
 $ result = mysql_query(“SELECT * FROM some_table”)
while($ row = mysql_fetch_array($ result)){
echo $ row ['id'。$ somenumber]; 
} 
  code>   pre> 
 
 

请帮助我以最好的方式使用mysqli,可能是oop风格我认为因为每个人都说最好的方式使用oop方式。 对不起,我只是在研究这个 p> div>

To do it with MySQLi OOP, you create an object, then call it's query() method.

$mysqli = new mysqli('hostname','user','password','databasename');
if (!$mysqli) {
  // connect failure, check connect_error()
  echo $mysqli->connect_error();
}
else {
  // Call query() to execute your SQL
  $result = $mysqli->query("SELECT * FROM some_table");
  if ($result) {
    // $result is an object of type mysqli_result
    // Call fetch_assoc() on $result
    while ($row = $result->fetch_assoc())
      echo $row['id'];
  }
}

If you have input parameters which you'll pass into your query, escape them with real_escape_string()

$somevar = $mysqli->real_escape_string($somevar);
$mysqli->query("SELECT * FROM sometable WHERE somecolumn='$somevar';");

The principle benefits of MySQLi over the older mysql_* API are

  • The ability to use prepared statements instead of dynamic SQL strings
  • Object-oriented behavior which can be extended with your own classes.