gpt4 book ai didi

php mysqli 按变量搜索不工作?

转载 作者:行者123 更新时间:2023-11-30 22:34:29 25 4
gpt4 key购买 nike

我正在尝试从数据库中获取数据,但变量 $dept 在查询中不起作用。当 result4 正常工作时,查询 result1、result2 和 result3 没有返回任何结果。变量 $dept 也是正确的,因为当我打印它的值时它打印(计算机)但在查询中它不起作用。请帮助我

<?php
if (isset($_POST['select_course'])) {
$dept = $_POST['department'];
$session = $_POST['session'];
$year = $_POST['year'];
$lab = $_POST['lab'];
$s_type = $_POST['s_type'];
$semester = $_POST['semester'];
$credit_h = $_POST['credit_h'];

$result1 = mysqli_query($con, "SELECT * FROM departments WHERE `name` = '$dept'");
$result2 = mysqli_query($con, "SELECT * FROM departments WHERE `name` = '".$dept."'");
$result3 = mysqli_query($con, "SELECT * FROM departments WHERE `name` =".mysqli_real_escape_string($dept));

$result4 = mysqli_query($con, "SELECT * FROM departments WHERE `name` = 'computer'");

while ($row = mysqli_fetch_array($result1)) {

echo $row['name'];
}
}
?>

最佳答案

if (isset($_POST['select_course'])) {
if ( !isset($_POST['department']) ) {
trigger_error('missing POST parameter "department"', E_USER_ERROR);
}
$query = sprintf("SELECT * FROM departments WHERE `name`='%s'", mysqli_real_escape_string($con, $_POST['department']));
$result = mysqli_query($con, $query);
if ( !$result ) {
trigger_error('query failed', E_USER_ERROR);
}
else {
while ( $row=mysqli_fetch_array($result) ) {
echo $row['name'], "\r\n";
}
}
}

如果这没有产生任何结果,请尝试

if (isset($_POST['select_course'])) {
if ( !isset($_POST['department']) ) {
trigger_error('missing POST parameter "department"', E_USER_ERROR);
}
$query = sprintf("SELECT Count(*) FROM departments WHERE `name`='%s'", mysqli_real_escape_string($con, $_POST['department']));
$result = mysqli_query($con, $query);
if ( !$result ) {
trigger_error('query failed', E_USER_ERROR);
}
else {
$row = mysqli_fetch_array($result);
echo '# of matching records: ', $row[0], "\r\n";
}
}

独立的小例子:

<?php
$con = new mysqli("localhost", "localonly", "localonly", "test");
if ($con->connect_errno) {
trigger_error('connect failed', E_USER_ERROR);
}
$con->query('CREATE TEMPORARY TABLE soFoo (`name` VARCHAR(32))');
$con->query("INSERT INTO soFoo (`name`) VALUES ('depa'),('depb'),('depc')");
$_POST = ['select_course'=>'1', 'department'=>'depb']; // <- it's only an example

if (isset($_POST['select_course'])) {
if ( !isset($_POST['department']) ) {
trigger_error('missing POST parameter "department"', E_USER_ERROR);
}
$query = sprintf("SELECT * FROM soFoo WHERE `name`='%s'", mysqli_real_escape_string($con, $_POST['department']));
$result = mysqli_query($con, $query);
if ( !$result ) {
trigger_error('query failed', E_USER_ERROR);
}
else {
while ( $row=mysqli_fetch_array($result) ) {
echo $row['name'], "\r\n";
}
}
}

关于php mysqli 按变量搜索不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32983663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com