This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 5 years ago.
I'm running PHP 7.0 and connected to a mysql db with a record matching the query in the below:
$query = mysqli_query($conn, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = 'baz'");
$row = mysqli_fetch_row($query);
print_r($row[0]);
Print outputs 1, as expected as there is only one record matching that username.
However, the following function returns false
function user_exists(){
$exists_query = mysqli_query($conn, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = 'baz'");
$row = mysqli_fetch_row($exists_query);
return ($row[0] == 1) ? True : False;
}
But I would expect it to be true. Am I misusing the fetch function?
What exactly does your first print_r statement output?
It should print an array, not an integer.
Your $row is an array of arrays.
So $row[0] will not be '1' but something like array('1').
I think it's because the $conn is not accessible. Try this
function user_exists(){
global $conn;
$exists_query = mysqli_query($conn, "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = 'baz'");
$row = mysqli_fetch_row($exists_query);
return ($row[0] == 1) ? True : False;
}
Edit:
As mentioned by #trs, you should consider your $row[0] output.
Related
This question already has answers here:
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
How do I display this query result:
from MySQL onto a webpage, just like this:
?
I want to display the count only. I did run the same query through PHP but its returning '2'. The PHP code is below
<?php
//Connection for database
$conn = mysqli_connect("localhost", "root", "aaaaa", "db");
$query = "SELECT `gender`,COUNT(`gender`) FROM `reg` GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result)
{
// it return number of rows in the table.
$row = mysqli_num_rows($result);
if ($row)
{
printf("" . $row);
}
// close the result.
mysqli_free_result($result);
}
// Connection close
mysqli_close($conn);
?>
Please note that I have gone through other answers like this one but I can't really find my way through, I want the value count only not the total number of all rows in the table, .e.g. count for 'Male'.
You're using mysqli_num_rows(), which returns the number of rows in the result, not the actual data in the result. For that you need to use mysqli_fetch_assoc().
Your could would become:
$query = "SELECT `gender`,
COUNT(`gender`) AS `count`
FROM `reg`
GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$gender = $row['gender'];
$count = $row['count'];
echo "$gender = $count<br>";
}
mysqli_free_result($result);
}
Note that I slightly changed your query to make the count accessible.
This question already has answers here:
How to solve PHP error 'Notice: Array to string conversion in...'
(6 answers)
Create PHP array from MySQL column
(12 answers)
Closed 2 years ago.
When I ran the following query in PHPMyAdmin, it returned the correct number of results. However when I try to echo the results in PHP, it only outputs one result, even when there is more thn one. How do I fix this so that every result is displayed?
$sql1 = "SELECT userFirstname FROM users WHERE userID IN (SELECT userID FROM note_editors WHERE noteID = (SELECT noteID FROM notes WHERE uniqueID = ?))";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header("Location: note-premium.php?error=sql");
exit();
}
else {
mysqli_stmt_bind_param($stmt1, "s", $unique);
mysqli_stmt_execute($stmt1);
$result1 = mysqli_stmt_get_result($stmt1);
while ($row1 = mysqli_fetch_assoc($result1)) {
$names = $row1['userFirstname'];
}
}
echo($names);
Second attempt: I tried creating an array. But this just outputs the word array and the error message, "Notice: Array to string conversion". Why?
$sql1 = "SELECT userFirstname FROM users WHERE userID IN (SELECT userID FROM note_editors WHERE noteID = (SELECT noteID FROM notes WHERE uniqueID = ?))";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header("Location: note-premium.php?error=sql");
exit();
}
else {
mysqli_stmt_bind_param($stmt1, "s", $unique);
mysqli_stmt_execute($stmt1);
$result1 = mysqli_stmt_get_result($stmt1);
$column = array();
while ($row1 = mysqli_fetch_assoc($result1)) {
$column[] = $row1['userFirstname'];
}
}
echo($column);
As you're looping through the results and storing the value of the column 'userFirstName' in $names, you're overwriting the previous value stored in it.
You've got two options - display the value as you're looping through the results, or store the value in an array and then display that afterwards.
Option 1 - display the value as you're looping through the results:
while ($row1 = mysqli_fetch_assoc($result1)) {
echo $row1['userFirstname'];
}
Option 2 - store the values in an array and display that after the loop
$names = [];
while ($row1 = mysqli_fetch_assoc($result1)) {
$names[] = $row1['userFirstname'];
}
foreach($names as $name) {
echo '<p>'.$name.'</p>';
}
Obviously you can customise how you want to loop through the array values and display them. I've wrapped each value in a <p> tag so that they display on a new line. If you just want to display the unformatted contents of the array, use print_r($names)
This question already has answers here:
SELECT COUNT(*) AS count - How to use this count
(5 answers)
Closed 1 year ago.
I'm trying to get the sum of a column from my database. When I try this code I get the error Undefined index: sum(col_1). How can I do this? I'm a real beginner so keep it a bit simple.
$sql = "SELECT * FROM table_1";
$run = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($run)){
$col_ans[1] = $rows['sum(col_1)'];
echo $col_ans[1];
}
You can easily find sum of a column this way.
$sql = "SELECT sum(col_1) as col_1_sum FROM table_1";
$run = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($run)){
echo $rows['col_1_sum'];
}
Your problem is that you didn't use the SUM() function inside your query, so you won't get any sum from the query
You can also try the following:
$query = "SELECT productName, SUM(productQty) AS 'Products Ordered'
FROM ctrlaproducttab
GROUP BY productName
";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result))
{
$productName = $row['productName'];
$itemsOrdered = $row['Products Ordered'];
}
Notice that we're giving an alias name Products Ordered to the result of expression SUM(productQty), and now we can use this alias name as an index in the associative array returned by mysqli_fetch_assoc()
This question already has answers here:
SELECT COUNT(*) AS count - How to use this count
(5 answers)
Closed 1 year ago.
I want to compare the result for count(*) with INT. This is my code;
$sql_check = "SELECT COUNT(*) FROM hd";
$result_check = mysqli_query($link, $sql_check) or die ("ERR");
$row = mysql_fetch_assoc($result_check);
if($row == 1)
{...}
It seem like there is no error. I tried to run it but it skip my if statement. If I tried to
echo $row
It show error
NOTICE: Array to string conversion
If I used code
$sql_check = "SELECT COUNT(*) FROM hd";
$result_check = mysqli_query($link, $sql_check) or die ("ERR");
$row = int($result_check);
if($row == 1)
{...}
It show error
NOTICE: Object of class msqli_result could not converted to int
I have tried to used the answers from previous questions that have been asked before this (same question) but it doesn't work. Can you help me? Please I really need to know where my false.
Thankyou for helping.
Some other questions (that have been asked) and I have tried it but it seem does not work for me:
1. Object of class mysqli_result could not be converted to int and all entries return true
2. mysqli_result could not be converted to int in
3. Object of class mysqli_result could not be converted to int - Can't find my Error
4. Convert SQL query object into integer
you can try this, not sure if it solves the problem!
$sql_check = "SELECT COUNT(*) FROM hd as 'res'";
$result_check = mysqli_query($link, $sql_check) or die ("ERR");
$row = mysql_fetch_assoc($result_check);
if($row['res'] == 1)
{...}
OR YOU CAN TRY THIS
$sql_check = "SELECT COUNT(*) FROM hd as 'res'";
$result_check = mysqli_query($link, $sql_check) or die ("ERR");
$row = mysql_fetch_assoc($result_check);
if((int)$row['res'] == 1)
{...}
This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
I have some php code that was like this:
$row = mysql_fetch_array ( mysql_query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'"));
I'm now trying to convert it to mysqli_fetch_array as shown here http://php.net/manual/en/mysqli-result.fetch-array.php (Example #1 Object oriented style)
I'm not sure what the example means by "$result".
This is what I've converted my code to so far:
<?php
include('../config.php');
if (isset($_GET['uid']) ) {
$uid = $_GET['uid'];
$id = $_GET['id'];
if (isset($_POST['submitted'])) {
foreach($_POST AS $key => $value) { $_POST[$key] = mysqli_real_escape_string($value); }
//Query for tblFacilityHrs
$sql = " UPDATE tblFacilityHrs SET `title`='{$_POST['title']}',`description`='{$_POST['description']}' WHERE `uid` = '$uid' ";
$result = $mysqli->query($sql) or die($mysqli->error);
//Query for tblFacilityHrsDateTimes
$sql2 = "UPDATE tblFacilityHrsDateTimes SET `startEventDate`='{$_POST['startEventDate']}',`endEventDate`='{$_POST['endEventDate']}', `startTime`='{$_POST['startTime']}',`endTime`='{$_POST['endTime']}',`days`='{$_POST['days']}',`recurrence`='{$_POST['recurrence']},`finalDate`='{$_POST['finalDate']}' WHERE `id` = '$id' "; print $sql2;
$result2 = $mysqli->query($sql2) or die($mysqli->error);
echo ($mysqli->affected_rows) ? "Edited row.<br />" : "Nothing changed. <br />";
echo "<a href='list.php'>Back</a>";
}
$row = $result->fetch_array($mysqli->query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'"));
$row2 = $result2->fetch_array($mysqli->query("SELECT * FROM `tblFacilityHrsDateTimes` WHERE `id` = '$id'"));
?>
There is probably a lot wrong with as I am learning mysqli, but right now it errors on
Fatal error: Call to a member function fetch_array()
UPDATE queries do not return result objects, it returns TRUE (assuming success). You're then trying to call TRUE->fetch_array(), which obviously won't work.
Now, for doing what you actually want to do, try this:
$row = $mysqli->query("SELECT.....")->fetch_array();
Looks like you are trying to use an old result object (result of your UPDATE) to get results for a new query. You need to run the new query first, assign its result to an object, and then fetch the results from object. Check out the last three lines of your script re-written:
$facilityHoursQueryResult = $mysqli->query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'");
$facilityHoursDateTimesQueryResult = $mysqli->query("SELECT * FROM `tblFacilityHrsDateTimes` WHERE `id` = '$id'");
$facilityHoursRow = $facilityHoursQueryResult == FALSE ? NULL : $facilityHoursQueryResult->fetch_array();
$facilityDateTimesRow = $facilityHoursDateTimesQueryResult == FALSE ? NULL : $facilityHoursDateTimesQueryResult->fetch_array();
?>
Here is a helpful page with other result object methods:
http://www.php.net/manual/en/class.mysqli-result.php