我一直试图创建搜索我的网站,当我尝试使用该变量时
SELECT size FROM tires WHERE size = $size'
我的搜索结果不合适。我得到的结果是
object(PDO)#@(0) {}
但我不确定为什么。我尝试过对搜索进行硬编码,效果很好。我也试过了
"SELECT size FROM tires WHERE size LIKE '%$size%'"
如果我使用fetchAll,这会从数据库中获得所有结果。如果我使用fetch(PDO::FETCH_ASSOC);
并且我只想从搜索框中输入的结果,它会给我一个部分结果。这是我搜索的代码:
<?php
require('database_connection.php');
$lifetime = 60 * 60 * 24 * 14; //2 weeks in seconds
session_set_cookie_params($lifetime, '/');
session_start();
//require_once('includes/functions.php');
include('index.html');
if(isset($_POST['size'])){
$_SESSION['size'] = $_POST['size'];
$size = $_SESSION['size'];
}
function tiresize() {
global $db;
if (isset($_POST['size'])){
$_SESSION['size'] = $_POST['size'];
$size = $_SESSION['size'];
// $size=mysql_real_escape_string($size);
// trim($size);
}
if (isset($size)){
$query = $db->prepare("SELECT size FROM tires WHERE size = '$size'");
$query->execute();
$tires = $query->fetchAll();
foreach ($tires as $name) {
echo "Tire Size: " .$name['size'];
if($query) // will return true if successful else it will return false
{
echo 'Query is working';// code here for true
};}}}
tiresize();
var_dump($db);
?>
var_dump($ db)给出一个对象(PDO)#1(0){}
这是表格:
<table><form action="search.php" method="post">
<tr><td>
<p>
<label for="searchSize" id="searchSize">Search Size:</label>
</p>
</td><td>
<p>
<input type="text" name="size" id="size" value="<?php echo $size['size']; ?> " /><br /><br /><br />
<input type="submit" name="size" value="Search" />
</p>
</td></tr></form>
</table>
答案 0 :(得分:0)
当在函数内部使用“global $size;
”时,它会从全局范围导入$size
变量,该范围可能是NULL
并覆盖本地$size
变量。您是否在$size
声明后检查了global
值?