[英]Using a session variable in a php mysql query with like
I've been trying to create a search for my website and when I try using the variable as in 我一直在尝试为我的网站创建搜索,而当我尝试使用如下所示的变量时
SELECT size FROM tires WHERE size = $size'
I don't get any results for my search. 我没有任何搜索结果。 I do get a result that says
我确实得到一个说的结果
object(PDO)#@(0) {}
but I'm not sure why. 但我不确定为什么。 I've tried hardcoding my search and it works perfectly.
我已经尝试对搜索进行硬编码,并且效果很好。 I've also tried
我也尝试过
"SELECT size FROM tires WHERE size LIKE '%$size%'"
and this gives me all the results from the database if I use fetchAll. 如果使用fetchAll,这将为我提供数据库的所有结果。 It gives me a partial result if I use
fetch(PDO::FETCH_ASSOC);
如果我使用
fetch(PDO::FETCH_ASSOC);
它会给我部分结果fetch(PDO::FETCH_ASSOC);
and I only want the results from what I put into the search box. 而且我只想要从搜索框中输入的结果。 HERE is the code that I have for the search:
这里是我用于搜索的代码:
<?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);
?>
The var_dump($db) gives a object(PDO)#1(0){} var_dump($ db)给出一个对象(PDO)#1(0){}
HERE IS THE FORM: 表格如下:
<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>
When " global $size;
" is used inside a function, it imports $size
variable from global scope, which perhaps is NULL
and overwrites local $size
variable. 当在函数内部使用“
global $size;
”时,它将从全局范围中导入$size
变量,该变量可能为NULL
并覆盖本地$size
变量。 Have you checked the $size
value after global
statement? 您是否在
global
语句后检查了$size
值?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.