我试图将MySql代码转换为MySqli。我的MySql工作得很好,但MySqli代码不起作用(它没有给出结果)。我不知道自己做错了什么,我是#No;"程序员。请你们纠正我的错误。
这是我的MySql代码:
<?php
session_start();
include 'dbh.php';
$name = $_POST['name'];
$desc = $_POST['desc'];
$placerId = $_SESSION['id'];
$null = "0";
if (isset($_SESSION['uid'])) {
$sql = "INSERT INTO adds (name, descr, placerId, imgURL)
VALUES ('$name', '$desc', '$placerId', '$null')";
$result = mysqli_query($conn, $sql);
$str = $_POST['keywords'];
$arr = explode(" ", $str);
$sql = "SELECT * FROM adds WHERE placerId='$placerId' ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$addId = $row['id'];
//print all the value which are in the array
foreach($arr as $keyword){
$sql = "INSERT INTO keywords (placerId, productId, keyword)
VALUES ('$placerId', '$addId', '$keyword')";
$result = mysqli_query($conn, $sql);
}
这是我的MySqli代码:
$name = $_POST['name'];
$desc = $_POST['desc'];
$placerId = $_SESSION['id'];
$null = "0";
if (isset($_SESSION['uid'])) {
if ($stmt = $mysqli->prepare("INSERT INTO adds (name, descr, placerId, imgURL) VALUES (?, ?, ?, ?)")) {
// Bind the variables to the parameter as strings.
$stmt->bind_param("ssss", $name, $desc, $placerId, $null);
// Execute the statement.
$stmt->execute();
// Close the prepared statement.
$stmt->close();
}
$str = $_POST['keywords'];
$arr = explode(" ", $str);
if ($stmt = $mysqli->prepare("SELECT id FROM adds WHERE placerId=? ORDER BY id DESC LIMIT 1")) {
// Bind a variable to the parameter as a string.
$stmt->bind_param("s", $placerId);
// Execute the statement.
$stmt->execute();
// Get the variables from the query.
$stmt->bind_result($addId);
// Fetch the data.
$stmt->fetch();
// Close the prepared statement.
$stmt->close();
foreach($arr as $keyword){
if ($stmt = $mysqli->prepare("INSERT INTO keywords (placerId, productId, keyword) VALUES (?, ?, ?)")) {
// Bind the variables to the parameter as strings.
$stmt->bind_param("sss", $placerId, $addId, $keyword);
// Execute the statement.
$stmt->execute();
// Close the prepared statement.
$stmt->close();
}
}
}
(连接数据库的$ conn变量)代码:
$conn = mysqli_connect("localhost", "root", "", "stp2");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error);
}