PHP MySQL - 作为整数的记录数
I'm trying to get the number of records in my database as an integer and use it in PHP to set certain conditions. My code consists of the following:
$sql = "SELECT COUNT(id) FROM sql_table";
$records = $conn->query($sql);
$record_count = $records->fetch_assoc();
I did a var_dump
of $record_count
and it returned an array: array(1) { ["COUNT(id)"]=> string(1) "4" }
. What I can't do is just access the number 4. I can access string(1) "4"
by accessing $record_count['COUNT(id)']
, but I can't find a way to access the number 4. If I try indexing, as in $record_count['COUNT(id)'][11]
, I get nothing. This value does not appear to be a straight string.
How can I access the number of records in the table as an integer for use in PHP?
我正在尝试将数据库中的记录数作为整数,并在PHP中使用它来设置某些 条件。 我的代码由以下内容组成: p>
$ sql =“SELECT COUNT(id)FROM sql_table”;
$ records = $ conn-> query($ sql);
$ record_count = $ records-> fetch_assoc();
code> pre>
我做了 $ record_count的 var_dump code> code>并返回一个数组: array(1){[“COUNT(id)”] => string(1)“4”} code>。 我不能做的只是访问数字4.我可以通过访问 $ record_count ['COUNT(id)'] code>访问 string(1)“4” code>, 但我找不到一种方法来访问数字4.如果我尝试索引,如 $ record_count ['COUNT(id)'] [11] code>,我什么也得不到。 此值似乎不是直字符串。
如何在PHP中使用表中的记录数作为整数? p>
div>
You can do it this way, but it's better to either use the internal num_rows in my opinion, or to do bind_result() to access COUNT(id) instead of using fetch assoc. That's just my style though :) This should work just fine for you.
$query = $sql->prepare("SELECT id FROM sql_table");
$query->execute();
$query->store_result();
$results = $query->num_rows;
$query->close();
echo $results;