这里我试图将变量传递给php select查询,但它不起作用。 无法弄清楚问题是什么。
代码:
<?php
$cname = $_GET['c_name'];
include 'config.php';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM co_details where co_name="$cname"';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "<br>";
echo "Course Details <br>";
echo $row['co_name']."<br>";
echo $row['co_objectives']."<br>";
echo $row['co_outline']."<br>";
echo $row['co_prereq']."<br>";
echo $row['co_fee']."<br>";
echo $row['co_duration']."<br>";
}
mysqli_close($conn);
}
?>
可能是什么原因? 如果我输入直接值,则代替变量$ cname,然后查询正在成功执行。
答案 0 :(得分:2)
请注意,您可以使用以下单引号字符串:
$sql = 'SELECT * FROM co_details where co_name="$cname"';
您认为在那里的那个变量不会被插值。它只能使用双引号字符串。
$sql = "SELECT * FROM co_details where co_name='$cname'";
正如@Fred在评论中所说,坚持使用MySQLi包括你的连接错误:
if(! $conn )
{
die('Could not connect: ' . mysql_error()); // mysql API doesn't belong
}
将其更改为MySQLi界面:
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
你应该使用prepared statements代替,因为这很容易引入SQL。
<?php
if(!empty($_GET['c_name'])) {
$cname = $_GET['c_name'];
include 'config.php';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
$sql = 'SELECT co_name, co_objectives, co_outline, co_prereq, co_fee, co_duration FROM co_details WHERE co_name = ?';
$select = $conn->prepare($sql);
$select->bind_param('s', $cname);
$select->execute();
$select->store_result();
$select->bind_result($co_name, $co_objectives, $co_outline, $co_prereq, $co_fee, $co_duration);
while($select->fetch()) {
echo "<br/>
Course Details: <br/>
$co_name <br/>
$co_objectives <br/>
$co_outline <br/>
$co_prereq <br/>
$co_fee <br/>
$co_duration <hr/>
";
}
}
?>
答案 1 :(得分:0)
您不能直接在字符串中使用$ cname:尝试如下所示:
$sql = "SELECT * FROM co_details where co_name='".$cname."'";
希望,这有帮助!
答案 2 :(得分:0)
您正在使用单引号不要像这样更改查询
$sql = "SELECT * FROM co_details where co_name='$cname'";