我无法在一个查询中更新两个表。还有其他方法吗?下面是我的代码示例。
$id = $_GET['idnum'];
$txtEditUsername=$_GET['txtEditUsername'];
$txtlname=$_GET['txtlname'];
$txtfname=$_GET['txtfname'];
$txtgender=$_GET['txtgender'];
$txtbdate=$_GET['txtbdate'];
$txtnationality=$_GET['txtnationality'];
$txtcnum=$_GET['txtcnum'];
$txtaddress=$_GET['txtaddress'];
$sql = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
$sql = "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname', ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (mysqli_query($conn, $sql)) {
} else {
echo "Error ".mysqli_error($conn);
}
答案 0 :(得分:1)
您可以像这样使用mysqli_multi_query
$sql = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
$sql .= "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname',
ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (mysqli_multi_query($conn, $query)) {
do {
/* sStockage du premier résultat */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* Affichage d'une séparation */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
}
} while (mysqli_next_result($conn));
}
在这里您可以进一步了解https://www.php.net/manual/en/mysqli.multi-query.php
答案 1 :(得分:0)
对于$sql
和$sql2
之类的变量,您应该使用不同的名称,但是您甚至可以使用一个查询,请尝试以下操作:
UPDATE users, people
SET users.u_username = '$txtEditUsername',
people.ppl_lname = '$txtlname',
people.ppl_fname = '$txtfname',
// AND SO ON
WHERE
users.u_uid = '$id'
AND people.ppl_id = '$id';
EDIT
但是,就像别人所说的那样,您可能成为sql注入的受害者。 尝试对PDO give a look here
使用预处理语句答案 2 :(得分:0)
问题在这里:
$sql = "UPDATE users ...";
$sql = "UPDATE people ...";
您正在使用相同的变量来执行两个不同的查询。第二条语句将覆盖第一个语句,并将其擦除。这就是users
表未更新的原因。
$usersSQL = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
if (!mysqli_query($conn, $usersSQL)) {
echo "Error while updating users table: ".mysqli_error($conn);
// Eventually, consider to exit the function..
}
$peopleSQL = "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname', ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (!mysqli_query($conn, $peopleSQL)) {
echo "Error while updating people table: ".mysqli_error($conn);
}
永远不要使用未经消毒的数据。 始终过滤并验证用户数据。
添加验证后,您将避免将无效值传递给查询(例如:ppl_lname
的长度最大为50个字符,而用户发送的是51个字符)。
最重要的是,从不永远不要将用户数据直接用于SQL查询,因为这会使数据库面临严重风险。