我正在尝试在函数中运行SQL语句,但是当我这样做时,没有任何反应。
这是我的代码......
<?php
$id = 47665;
function call($id)
{
$getBookTitle = $this->EE->db->query("SELECT b.title
FROM books as b
WHERE b.side = 'open'
AND b.swarm_suit = 1
AND b.book_id = ".$id. "
");
$variable;
foreach ($getBookTitle ->result_array() as $key)
{
$variable = $key['title'];
}
echo $variable;
}
call(0254);
?>
如果我在函数外部运行此SQL语句,它将完美运行。
帮助,有人吗?
答案 0 :(得分:1)
你的foreach正在迭代一个不存在的变量。
不应该是foreach( $getBookTitle
关于你所涉及的范围问题。我建议你定义一个新的数据库句柄。
$mysqli = new mysqli("localhost", "my_user", "my_password", "database");
$mysqli->query("SELECT b.title
FROM books as b
WHERE b.side = 'open'
AND b.swarm_suit = 1
AND b.book_id = ".$id. "
");
答案 1 :(得分:0)
什么?未定义的$getRestaurantName
?
他在函数中使用$this
,而不是在对象方法中使用!
<?php
$id = 47665;
function call($id)
{
/*
* What is $this? Where is class?
*/
$getBookTitle = $this->EE->db->query("SELECT b.title
FROM books as b
WHERE b.side = 'open'
AND b.swarm_suit = 1
AND b.book_id = ".$id. "
");
$variable; // Notice: undefined variable
foreach ($getBookTitle ->result_array() as $key)
{
$variable = $key['title'];
}
echo $variable;
}
似乎你很简单就关闭了所有的PHP错误和警告。
<?php
// Just for example
class _class {
public $EE; // Your 'EE' definition
private static $instance;
public static function getInstance() {
if(!self::$instance) self::$instance = new self();
return self::$instance;
}
}
function call($id)
{
$obj = _class::getInstance(); // You should get instance of object where 'EE' defined. Use singletone pattern for this.
$getBookTitle = $obj->EE->db->query("SELECT b.title
FROM books as b
WHERE b.side = 'open'
AND b.swarm_suit = 1
AND b.book_id = ".$id. "
");
$variable = NULL;
foreach ($getBookTitle ->result_array() as $key)
{
$variable = $key['title'];
}
echo $variable;
}
call(0254);