This question already has an answer here:
Going to make this quick. So I am doing something that should be relatively simple but none of the answers I have found online (Yes, I have read through and implemented them ALL) have yielded the right result.
Basically, all I am trying to do is count how many times a specific field shows up in a column in one of my databases. Sounds easy, right?
Well, this is where it gets a bit sketchy for me. The query I am trying to use to attain this information is this:
$sql2 = "SELECT user_id COUNT(*) FROM ch_documents_list WHERE user_id = $users_id ";
From here, I want to take the result as an int
and echo
it into a specific part of the site (not important as to where exactly).
The only way I can get information out of the result is to run a print_r($result)
Where $result
is set to the response of the query.
NOTE The information printed looks like this:
mysqli_result Object ( [current_field] => 0 [field_count] => 5 [lengths] => [num_rows] => 1 [type] => 0 )
Which, as many of you can figure out, is useless. What changes do I need to make in order to get this right?
Thanks everyone!
Pasting more of my code below
Query As Of Now
$dbname_classes = "classes";
$conn2 = new mysqli($servername, $username, $password, $dbname_classes);
$sql2 = "SELECT user_id, COUNT(*) AS total FROM ch_documents_list WHERE user_id = $users_id";
$result2 = $conn->query($sql);
$row = mysqli_fetch_assoc($result2);
Then below in the html
<div class='overview-stat'><?php echo $row['total']; ?></div>
Which leads to this: Notice: Undefined index: total
</div>
Try this code
$query = "SELECT * FROM ch_documents_list WHERE user_id = $users_id ";
$result = mysqli_query($con,$query );
$rows = mysqli_num_rows($result);
print_r($rows);
Using the SQL AS
Keyword
Rewrite your query like this below query:
$sql2 = "SELECT user_id, COUNT(*) AS total FROM ch_documents_list WHERE user_id = $users_id";
After that just index your result array using the total key and boom you got your int counts
Like: $result['total']
May this be helpful.
$sql2 = "SELECT COUNT(*) as total FROM ch_documents_list WHERE user_id = $users_id";
$result = mysqli_query($con,$sql2); // $con is Boolean returned from mysqli_connect()
$row = mysqli_fetch_array($result);
echo $row["total"];
return int two query example:
1. $sql2 = "SELECT COUNT(user_id) as id FROM ch_documents_list WHERE user_id = $users_id";
**You should return count
mysql_num_rows
**
$conn = mysqli_connect("localhost", "username", "password", "databasename");
$result = mysqli_query($conn, "SELECT user_id FROM ch_documents_list WHERE user_id = $users_id");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows
";
this is mysqli function support
May not the propper way, but works fine for me since years:
$sql2 = "SELECT user_id COUNT(*) AS total FROM ch_documents_list WHERE user_id = $users_id";
$result = mysqli_fetch_assoc($sql2)
You can then access it with
$result['total']