我正在學習PHP,所以我在PHP中練習SQL和CRUD,但是我似乎有一個問題,但我沒有看到什麼是錯的。有兩個文件:此PHP代碼中的SQL語法有什麼問題?
databases.php
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occured
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
// Perform database query
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if (!$result) {
die("Database query failed.");
}
?>
<!DOCTYPE html PUBLIC "-//W3C/DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Databases</title>
<body>
<ul>
<?php
// 3. Use returned data (if any)
while($subject = mysqli_fetch_assoc($result)) {
// Output data from each row
?>
<li><?php echo $subject["menu_name"] . " (" .$subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
<?php
// 4. Release returned data
mysqli_free_result($result);
?>
</body>
<?php
// Close database connection
mysqli_close($connection);
?>
和databases_update.php
<?php
// 1. Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occured
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
// Often these are form values in $_POST
$id = 5;
$menu_name = "Delete me";
$position = 4;
$visible = 1;
// 2. Perform database query
$query = "UPDATE subjects SET ";
$query .= "menu_name = '{$menu_name}', ";
$query .= "position = {$position}, ";
$query .= "visible = {$visible}, ";
$query .= "WHERE id = {$id}";
$result = mysqli_query($connection, $query);
// Test if there was a query error
if ($result) {
// Success
// redirect_to("somepage.php");
echo "Success!";
} else {
// Failure
// message = "Subject creation failed";
die("Database query failed. " . mysqli_error($connection));
}
?>
<!DOCTYPE html PUBLIC "-//W3C/DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Databases</title>
<body>
</body>
<?php
// Close database connection
mysqli_close($connection);
?>
我收到的錯誤是,當我去到localhost:8888/databases_update.php。 這是錯誤: Database query failed. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 5' at line 1
這是什麼造成的?
丟失後'可見逗號= {$可見}' –
你有後'{$可見}'一個逗號。 – h2ooooooo
您應該使用準備好的語句。如果可以幫助,請不要將變量直接放入查詢中。 – Mike