我的PHP脚本存在一些问题。
我有一个存储在PHP文件中的PHP函数,我正在尝试从另一个脚本运行该PHP函数。
所以用代码解释自己:
like.inc.php:
function post_exists($id) {
$host = "example";
$username = "example";
$password = "example";
$database = "example";
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("SELECT COUNT(`id`) AS `count` FROM `posts` WHERE `id` = '$id'");
while ( $row = $objQuery->fetch_object() ) {
if ( $row->count == 1 ) return true;
}
}
profile.php:
include ( 'like.inc.php' );
if (post_exists(70) === true) {
echo 'Exists!';
}
存在ID为70的帖子,因此它应该回显Exists!但它只是崩溃了我的一半页面。也许它没有正确加载?
任何帮助都将受到高度赞赏!
答案 0 :(得分:1)
$objQuery
必须$query
的位置。试试这段代码:
function post_exists($id) {
$host = "example";
$username = "example";
$password = "example";
$database = "example";
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("SELECT COUNT(`id`) AS `count` FROM `posts` WHERE `id` = '$id'");
while ( $row = $query->fetch_object() ) {
if ( $row->count == 1 ) return true;
}
}
答案 1 :(得分:1)
你可以用不同的方式编写函数:
function post_exists($id) {
$host = "example";
$username = "example";
$password = "example";
$database = "example";
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
// Instead of getting count, just get the row and
// do the count with PHP
$query = $connection->query("SELECT * FROM `posts` WHERE `id` = '$id' LIMIT 1");
if($query){
return $query->num_rows > 0;
}
return false;
}