[英]How to get and store a value into a variable from SQL query php
我正在嘗試將sql查詢的結果存儲到我的php查詢中的變量中。 但是事實是,它不起作用,僅僅是因為我犯了小學生錯誤以及由於我缺乏php經驗。
這是我的代碼:
<?php
if(!empty($_POST['driverNo'])){
$driverNoText = $_POST['driverNo'];
$stmt = "SELECT registrationNo FROM cars WHERE driverNo = ?";
$result = $conn->prepare($stmt);
$result->bind_param('s', $driverNoText);
$result->execute();
$result->store_result();
if($result->num_rows > 0){
$registrationNo = $result["registrationNo"];
echo $registrationNo;
}
else{
$registrationNo = "";
}
}
else{
echo "Something went horribly wrong";
}
?>
我只想將registrationNo存儲到$ registrationNo中,因為稍后需要在其他地方使用該值。
如果有人可以幫助我修復錯誤,那將意味着很多
謝謝
您試圖錯誤地訪問該值。 它不是數組,請嘗試替換此數組:
$registrationNo = $result["registrationNo"];
有了這個:
$registrationNo = $result[0]->registrationNo;
希望有幫助!
您有確切的想法要面對什么嗎?
您可以嘗試調試。 嘗試這樣的事情:
$stmt = "SELECT registrationNo FROM cars WHERE driverNo = ?";
$result = $conn->prepare($stmt) or die( mysqli_error($dbh) ); // Where $dbh = mysqli_connect("localhost","root", "password", "database");
$result->bind_param('s', $driverNoText);
$result->execute() or die( mysqli_stmt_error($result) );
//$result->store_result();
/* I'd prefer you to use bind result instead */
$result->bind_result($registrationNo);
echo $registrationNo; // This must show the registration no.
希望這可以幫助。
和平! xD
試試這個:(用於數組獲取)
<?php
// your codes ...
$result->bind_param('s', $driverNoText);
$result->execute();
$result->bind_result($col);
if($result->num_rows > 0){
while ($result->fetch()){
$registrationNo = $col;
echo $registrationNo."<br/>";
}
} else{
$registrationNo = '';
echo $registrationNo."<br/>";
}
// your code ...
?>
現在,$ result是一個數組,用於保存表中的整個數據行,但是由於您要返回的是單個值而不是完整的行,因此可以使用以下命令:
$sql = "SELECT registrationNo FROM cars WHERE driverNo = " . $_POST['driverNo'];
$registrationNo = $conn->query($sql)->fetch_row()[0];
基本上,這會將查詢返回的數組轉儲到fetch_row()
,並且[0]
僅訪問該數組中的第一個元素。 由於您僅在SQL中指定了單個字段,因此該數組中的第一個值應該是所需的數據。
如果您想保留所有代碼,則可以通過以下方式進行更改:
$registrationNo = $result->fetch_row()[0];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.