我的PHP脚本有一些问题。
我有一个PHP函数,它存储在一个PHP文件中,我正试图从另一个脚本运行该PHP函数。
所以用代码来解释我自己:
类似.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!但它只是崩溃了我的一半页面。所以也许它没有正确加载?
如有任何帮助,我们将不胜感激!
有$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;
}
}
您可以用不同的方式编写函数,如下所示:
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;
}