初學PHP/Mysql在這裏。 我有一個文件clientdetails.php,它使用GET方法連接到Mysql數據庫並檢索數據(下面的代碼的上半部分)。在同一個文件中,我有引導選項卡。在其中一個選項卡上,我想運行另一個Mysql查詢以從同一數據庫獲取不同的數據。在同一個文件上的PHP/Mysql多查詢
我得到的錯誤是:
Warning: mysqli::query(): Couldn't fetch mysqli in C:\wamp64\www\crud\clientdetails.php on line 51
我懷疑這事做的連接已經存在?
這是clientdetails.php的簡化版本:
<?php
// Check existence of id parameter before processing further
if(isset($_GET["client_id"]) && !empty(trim($_GET["client_id"]))){
// Include config file
require_once 'config.php';
// Prepare a select statement
$sql = "SELECT * FROM client WHERE client_id = ?";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("i", $param_id);
// Set parameters
$param_id = trim($_GET["client_id"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
$result = $stmt->get_result();
if($result->num_rows == 1){
/* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */
$row = $result->fetch_array(MYSQLI_ASSOC);
// Retrieve individual field value
} else{
// URL doesn't contain valid id parameter. Redirect to error page
header("location: error.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
// Close connection
$mysqli->close();
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
?>
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#sectionA">Details</a></li>
</ul>
<div class="tab-content">
<div id="Account" class="tab-pane fade">
<div class="form-group">
<?php
// Include config file
require_once 'config.php';
// Attempt select query execution
$sql = "SELECT transaction FROM client";
if($result = $mysqli->query($sql)){
if($result->num_rows > 0){
echo "<table class='table table-bordered table-striped'>";
echo "<thead>";
echo "<tr>";
echo "<th>#</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = $result->fetch_array()){
echo "<tr>";
echo "<td>" . $row['client_id'] . "</td>";
echo "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
$result2->free();
} else{
echo "<p class='lead'><em>No records were found.</em></p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
// Close connection
$mysqli->close();
?>
</div>
</div>
</div>
配置文件:
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'mypassword');
define('DB_NAME', 'mydatabase');
/* Attempt to connect to MySQL database */
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
?>
show ur config.php –
這已完成 – wazzahenry
不要關閉連接嗎? – WheatBeak