使用mysqli()

时间:2016-10-22 13:14:55

标签: php mysql mysqli

使用mysqli()转换以下PHP代码。

以下代码在php 7中不起作用,我不知道如何使用mysqli()。所以,任何人都可以帮助使用mysqli()更改以下代码。

以下代码用于连接数据库以添加论坛的答案。在这里,我尝试使用xampp和select database连接我的本地服务器(这里,db_name =“test1”)。然后我试图获取从隐藏字段发送的id的值并找到最高答案号。之后它将向最高答案号添加+ 1并将其保存在变量名“$ Max_id”中,如果没有答案,则设置它= 1.然后它将再次获取从表单发送的值并创建日期和时间。之后它将插入答案。如果添加了新答案,则在答复列中添加值+1,最后连接将关闭。

   <?php

$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test1"; // Database name
$tbl_name="forum_answer"; // Table name

// Connect to server and select databse.


mysql_connect("$host", "$username", "$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

// Get value of id that sent from hidden field
$id=$_POST['id'];

// Find highest answer number.
$sql="SELECT MAX(a_id) AS Maxa_id FROM $tbl_name WHERE question_id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);

// add + 1 to highest answer number and keep it in variable name "$Max_id". if there no answer yet set it = 1
if ($rows) {
$Max_id = $rows['Maxa_id']+1;
}
else {
$Max_id = 1;
}

// get values that sent from form
$a_name=$_POST['a_name'];
$a_email=$_POST['a_email'];
$a_answer=$_POST['a_answer'];

$datetime=date("d/m/y H:i:s"); // create date and time


// Insert answer
$sql2="INSERT INTO $tbl_name(question_id, a_id, a_name, a_email, a_answer, a_datetime)VALUES('$id', '$Max_id', '$a_name', '$a_email', '$a_answer', '$datetime')";
$result2=mysql_query($sql2);

if($result2){
echo "Successful<BR>";
echo "<a href='view_topic.php?id=".$id."'>View your answer</a>";


// If added new answer, add value +1 in reply column
$tbl_name2="forum_question";
$sql3="UPDATE $tbl_name2 SET reply='$Max_id' WHERE id='$id'";
$result3=mysql_query($sql3);

}
else {
echo "ERROR";
}

// Close connection

mysql_close();
?>

1 个答案:

答案 0 :(得分:0)

//DB Connection
$dbserver    = "...";
$dbusername  = "...";
$dbpassword  = "...";
$db          = "...";

//create Connnection
$conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);

//check Connection
if($conn->connect_error)
{
    die("connection failed: ".$conn->connect_error);
}

$sql="";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);

更改为

$sql = "";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);

还要注意

mysql_close();