1

我试图弄清楚如何使用带有 where 子句的数组变量。

当我回显 $deader 时,我得到 23、25、43、56、31、24、64、34 等 .. 这些是我想要更新的 id 号码

$sql = mysql_query("UPDATE users SET dead='DEAD' WHERE userID ='(".$deader.")' ");

该数组$deader有多个 id 编号值,它只工作并更新 $deader 数组中的第一个 id#。

我正在阅读 Implode 是我需要的,但不知道如何将其转换为功能格式。

4

4 回答 4

4

Use WHERE ... IN

$sql = mysql_query("UPDATE users SET dead='DEAD' WHERE userID IN (".$deader.")");

Where $deader is in comma separated format. (for example: $deader = '143, 554, 32')

If it is an array you can use $deader = implode(',', $deader); to make it comma separated.


Note: Please stop using mysql_* functions for new code. The functions aren't maintained anymore and the community has begun the deprecation process. See here for more info about converting this to PDO: How do I convert a dynamically constructed ext/mysql query to a PDO prepared statement? (thanks to PeeHaa)

于 2012-09-12T19:43:47.877 回答
1

If $deader is some sort of string of values, you will need to use MySQL IN() condition. Like this

UPDATE users SET dead = 'DEAD" WHERE userID IN ('?', '?', '?')

Where ? are your values. If userID as an INTEGER field, you can omit the single quotes around the values, if it is a string field, they would be required.

于 2012-09-12T19:45:26.130 回答
0

I think what you're looking for is the IN keyword in SQL.

UPDATE users set dead='DEAD' where userID in (100,101,102)
于 2012-09-12T19:44:38.667 回答
-1

使用 MySQLi 而不是 mysql_*

require_once('.dbase'); //contains db constants DB_NAME, DB_USER etc
//using PHP built in connection class mysqli

$mysqli = new mysqli(DB_HOST,DB_UNAME,DB_UPWORD,DB_NAME);

if ($mysqli->connect_errno){
    $err = urlencode("Failed to open database connection: ".$mysqli->connect_error);
    header("Location: error.php?err=$err");
exit();
    }
$deader=implode(',',$deader); //assumes array, sting "143,554,32"
if ($stmt = $mysqli->prepare("UPDATE users SET dead='DEAD' WHERE userID IN (?)"){
    //bind variable to statement object
    $stmt->bind_param('s',$deader) //var type[string],var to bind
    //execute query
    $stmt->execute();
    //feedback
    $rowsAffected = $stmt->affected_rows(); //update doesn't return a result set.
    //close statement object
    $stmt->close();
}
$mysqli->close();

你们正在抨击 Rickos 使用 mysql_* 但没有解释如何使用它,我的意思只是展示如何使用 mysqli。准备好的语句不是必需的,但是由于您将我的评论标记为(peehaa),因为它没有将其显示为准备好的语句,因此这里将其编辑为准备好的语句。它确实回答了他的问题。

于 2012-09-12T20:02:11.180 回答