将我已弃用的​​mysql转换为mysqli

时间:2014-08-24 05:21:40

标签: php mysql mysqli

我是初学者,我需要学习从mysql转换为mysqli的基本知识。我想先从配置开始。我已经使用了这个connect.php,它现在正在工作,我想切换到未预订的mysqli。请告诉我如何修改这个脚本。

<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "nopassword";
$dbname = "student";

$link_id = mysql_connect($host, $dbusername, $dbpassword);
if(!$link_id){
    die(mysql_error("Can`t Connect To database")); 
}
else{
    $db = mysql_select_db($dbname, $link_id);
}     
if(!$db){
    die(mysql_error("Can`t select database")); 
}     
return;

&GT;

1 个答案:

答案 0 :(得分:0)

根据我的评论......

你可以这样做

$host       = "localhost";
$dbusername = "root";
$dbpassword = "nopassword";
$dbname     = "student";

$link = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link)); 

$query   = "SELECT knowhow FROM google WHERE myknowhow='leaks'";
$knowhow = mysqli_query($link, $query); 

这是你能做到的最简单的方法。

但你应该像这样使用它(OOP)

$db      = new mysqli($host,$dbusername,$dbpassword,$dbname);
$knowhow = $db->query("SELECT knowhow FROM google WHERE myknowhow='leaks'");

根据你的评论:

您不再需要IF / ELSE语句。所有错误都可以通过

获取
die("Error " . mysqli_error($link));

在oop中,错误记录在

... new mysqli($host,$dbusername,$dbpassword,$dbname);

修改

由于您在阻止询问新问题的情况下,只需更新此问题:

$link    = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link)); 
$query   = "SELECT * FROM student_information where student_id='{$_SESSION['user_id']}'";
$knowhow = mysqli_query($link, $query);

$data    = mysqli_fetch_array($result);     
$numRows = mysqli_num_rows($result); 

$i = 0;     
while($i < $numRows){
    echo $data[$i++] . "<br />";
}

// I would not use a while in this case. I would prefere a foreach
// just to prevent from using a endless loop and 1 row less code :)

foreach($data as $d){
    echo $d . "<br />";
}

请使用MySqli作为类,如$ db = new Mysqli();