我想使用PHP在MySQL中更新我的学生表,但它不起作用,我不知道我犯了什么错误:/
这是我的代码。
BTW我在id周围加上引号,因为varchar
不是int
。
它只是说数据没有更新。
<?php
// PHP code to update data from MySQL database table
if(isset($_POST['update']))
{
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "students";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
// get values form input text and number
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$country=$_POST['country'];
$phone=$_POST['phone'];
$email=$_POST['email'];
// mysql query to Update data
$query = "UPDATE `students` SET `fname`='".$fname."',`lname`='".$lname."',`Nationality`='".$country."',`PhoneNumber`=$phone,`Email`='".$email."',`age`= $age WHERE `id` = '$id'";
$result = mysqli_query($connect, $query);
if($result)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
mysqli_close($connect);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP INSERT DATA USING PDO</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="updating.php" method="post">
<input type="text" name="id" placeholder="Enter new ID"><br><br>
<input type="text" name="fname" placeholder="Enter new First Name"><br><br>
<input type="text" name="lname" placeholder="Enter new Last Name"><br><br>
<input type="number" name="age" placeholder="Enter new age" min="13" max="90"><br><br>
<input type="text" name="country" placeholder="Enter new Nationality"><br><br>
<input type="number" name="phone" placeholder="Enter new Phone Number"><br><br>
<input type="text" name="email" placeholder="Enter new Email"><br><br>
<input type="submit" name="update" value="update">
</form>
</body>
</html>
答案 0 :(得分:0)
我认为您的$query
变量很糟糕。查看以下查询。这应该可以解决您的问题。
$query = "UPDATE students SET fname= '$fname', lname = '$lname', Nationality = '$country', PhoneNumber = '$phone', Email= '$email', age = '$age' WHERE id = '$id'";
我认为你的错误是你没有用单引号包裹$age
。无论是整数还是字符串,只要需要更新它就需要用单引号来包装它。
答案 1 :(得分:0)
您的查询写错了:
应该是:
$query = "UPDATE `students` SET `fname`='" . $fname . "',`lname`='" . $lname . "',`Nationality`='" . $country . "',`PhoneNumber`=" . $phone . ",`Email`='".$email."',`age`= " . $age . " WHERE `id` = '" . $id . "'";
<强> N.B。 :假设您的年龄和电话是INT类型数据。
此查询执行$ query后将是:
UPDATE `students` SET `fname`='john',`lname`='adams',`Nationality`='usa',`PhoneNumber`=456123789,`Email`='aa@bb.com',`age`= 23 WHERE `id` = '1'
如果年龄和电话是CHAR,则查询将如下所示:
$query = "UPDATE `students` SET `fname`='" . $fname . "',`lname`='" . $lname . "',`Nationality`='" . $country . "',`PhoneNumber`='" . $phone . "',`Email`='".$email."',`age`= '" . $age . "' WHERE `id` = '" . $id . "'";
此查询执行$ query后将是:
UPDATE `students` SET `fname`='john',`lname`='adams',`Nationality`='usa',`PhoneNumber`='456123789',`Email`='aa@bb.com',`age`= '23' WHERE `id` = '1'
希望它能解决问题。
谢谢和问候