問題描述
我需要一些幫助,以便在我的代碼中執行 foreach.
I would like some help to execute a foreach into my code.
我將多個值發布到用戶名中:作為 username[0] = user1 , user2
I post multiple value into username : as username[0] = user1 , user2
但是我的 foreach 給我的結果只是最后一個條目或什么都沒有.
but my foreach gives me result like only the last entry or nothing.
$companyname = $_POST['companyname'];
$username_grab = $_POST['username'];
$username = implode(",", $username_grab);
foreach ($username_grab as $value){
$value = $username_grab;
$sql = "select * from linked_user where username = '$value' and company_name = '$companyname'";
$res = mysqli_query($conn,$value);
while($row = mysqli_fetch_array($res)){
$returnValue['username'] = $row['username'];
$returnValue['user_scid'] = $row['user_scid'];
}
}
echo json_encode($returnValue);
?>
推薦答案
您要執行的任務是帶有可變數量占位符的準備好的語句.這在 PDO 中更簡單,但我將向您展示 mysqli 面向對象風格的方法.不管怎樣,總是打印一個 json 編碼的數組,這樣你的接收腳本就知道需要什么樣的數據類型.
The task you are to perform is a prepared statement with a variable number of placeholders. This is simpler in PDO, but I'll show you the mysqli object-oriented style approach. No matter what, always print a json encoded array so that your receiving script knows what kind of data type to expect.
我有一個片段,其中包括一整套診斷和錯誤檢查.我沒有測試過這個腳本,但它與我的這篇文章非常相似.
I had a snippet laying around that includes a full battery of diagnostics and error checking. I have not tested this script, but it has quite the resemblance to this post of mine.
if (empty($_POST['companyname']) || empty($_POST['username'])) { // perform any validations here before doing any other processing
exit(json_encode([]));
}
$config = ['localhost', 'root', '', 'dbname']; // your connection credentials or use an include file
$values = array_merge([$_POST['companyname']], explode(',', $_POST['username'])); // create 1-dim array of dynamic length
$count = sizeof($values);
$placeholders = implode(',', array_fill(0, $count - 1, '?')); // -1 because companyname placeholder is manually written into query
$param_types = str_repeat('s', $count);
if (!$conn = new mysqli(...$config)) {
exit(json_encode("MySQL Connection Error: <b>Check config values</b>")); // $conn->connect_error
}
if (!$stmt = $conn->prepare("SELECT user_scid, user_scid FROM linked_user WHERE company_name = ? AND username IN ({$placeholders})")) {
exit(json_encode("MySQL Query Syntax Error: <b>Failed to prepare query</b>")); // $conn->error
}
if (!$stmt->bind_param($param_types, ...$values)) {
exit(json_encode("MySQL Query Syntax Error: <b>Failed to bind placeholders and data</b>")); // $stmt->error;
}
if (!$stmt->execute()) {
exit(json_encode("MySQL Query Syntax Error: <b>Execution of prepared statement failed.</b>")); // $stmt->error;
}
if (!$result = $stmt->get_result()) {
exit(json_encode("MySQL Query Syntax Error: <b>Get Result failed.</b>")); // $stmt->error;
}
exit(json_encode($result->fetch_all(MYSQLI_ASSOC)));
如果您不想要所有這些診斷條件和評論的膨脹,這里是應該執行相同的基本等效:
If you don't want the bloat of all of those diagnostic conditions and comments, here is the bare bones equivalent which should perform identically:
if (empty($_POST['companyname']) || empty($_POST['username'])) {
exit(json_encode([]));
}
$values = explode(',', $_POST['username']);
$values[] = $_POST['companyname'];
$count = count($values);
$placeholders = implode(',', array_fill(0, $count - 1, '?'));
$param_types = str_repeat('s', $count);
$conn = new mysqli('localhost', 'root', '', 'dbname');
$stmt = $conn->prepare("SELECT user_scid, user_scid FROM linked_user WHERE username IN ({$placeholders}) AND company_name = ?");
$stmt->bind_param($param_types, ...$values);
$stmt->execute();
$result = $stmt->get_result();
exit(json_encode($result->fetch_all(MYSQLI_ASSOC)));
這篇關于如何使用 mysqli 編寫一個安全的 SELECT 查詢,該查詢具有可變數量的用戶提供的值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!