I have a table and i'm trying to extract the maximum value of a column called order_num, which has 33 intries of integers 1 through 33. I want the value "33" in this instance as its the highest number.
$userid is an integer derived from a one row table with a field id that I am trying to retrieve
//get the currentUser ID so we know whos deck to ammend
$userIDSQL = "SELECT id FROM currentUser";
$userIdResult = mysqli_query($db, $userIDSQL) or die("SQL Error on fetching user ID: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_assoc($userIdResult)) {
$result_array[] = $row['id'];
}
//the actual user id
$userId = $row['id'];
echo "user id is " . $userId;
Doing a print_r on $userId shows the array to be empty, that's why the code below doesn't work.. :(
...
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
$result_array[] = $row['MAX(order_num)'];
echo "the result is" . $result_array['order_num'];
echo "the result is" . $row['order_num'];
echo "the result is" . $result_array['MAX(order_num)']; //tried different methods to get the output.
}
The output I get is
the result is the result is the result is
Does anyone know why i'm not able to get the result from the table?
Edit:
Okay, try this:
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
print_r($row);
}
What do you get?
Your first code to get the userId doesn't work because of your usage of the array, change to:
$userId = 0;
while ($row = mysqli_fetch_assoc($userIdResult)) {
$userId = $row['id'];
}
As I've shown below, if you only expect a single row then remove the while loop and just call fetch_assoc a single time.
Given you only want the single row you don't need the while loop:
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId' LIMIT 1";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
if($reOrderDeckResult && mysqli_num_rows($reOrderDeckResult) == 1)
{
$row = mysqli_fetch_assoc($reOrderDeckResult);
echo 'result: ' . $row['order_num'];
}
else
{
echo 'No rows found!!';
}
I also added LIMIT 1 to the query, and a check to see if there are any rows.
You have renamed your MAX(order_num) AS order_num so you should try to get value using order_num only as echo $result_array['order_num']
and in while you should check whether you are getting value or not by placing below code in while loop
echo '<PRE>';
print_r($row);
echo '</PRE>';
This may helps you..,
<?php
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
//you have to use the alias name not aggregate function title
$result_array[] = $row['order_num'];
echo "the result is" . $result_array['order_num'];
echo "the result is" . $row['order_num'];
//you have to use the alias name not aggregate function title
echo "the result is" . $result_array['order_num']; //tried different methods to get the output.
}
Related
I'm going to count the sum of the value in rmNum column and with the same value of rmType.
From the table as shown in image above, can someone please teach how to to sum up the value of rmNum by referring to the same "keyword" of rmType?
i am new to PHP and i still get confusing about this even i went through the teaching part in other websites and questions that asked in Stackoverflow.
Edit 2:
<?php
require_once 'dbconnect.php';
$sql = "SELECT * FROM room";
$result = mysqli_query($conn, $sql);
echo $conn->error;
while($row = mysqli_fetch_array($result)) {
$typeRow = $row;
}
$sql1 = "SELECT rmType, SUM(rmNum) as total FROM room GROUP BY rmType";
$result = mysqli_query($conn,$sql1);
while ($row1 = mysqli_fetch_assoc($result)) {
echo $row1['rmType'] . ' had ' . $row1['total'] . ' room reservations';
}
mysqli_close($conn);
?>
this is the coding i used after all, it still give me Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean
You can use a GROUP BY statement:
$sql = "SELECT rmType, SUM(rmNum) as total FROM table GROUP BY rmType";
where table is the name of the table. This will return a table with two columns: the rmType and the total sum of rmNum for that type.
You can then process it like:
$sql = "SELECT rmType, SUM(rmNum) as total FROM table GROUP BY rmType";
$result = $mysqli->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row['rmType'] . ' had ' . $row['total'] . ' room reservations';
}
EDIT: In case you want the total sum, you do not need to group, you can simply use:
$sql = "SELECT SUM(rmNum) as total FROM table";
$result = $mysqli->query($sql);
if ($row = $result->fetch_assoc()) {
echo 'The total number of reservation rooms is ' . $row['total'];
}
I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.
$sql = "SELECT title, article, filename, caption FROM articles
INNER JOIN images WHERE articles.image_id = images.image_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
var_dump($row);
This only grabs the first row in the db when what I need is for it to grab all rows. How can I achieve this?
fetch_assoc() returns the next row of the result set with each call, so you need to call it in a loop like this:
while($row = $result->fetch_assoc()) {
var_dump($row);
}
The loop ends when $row = null (i.e. there's no more rows in the result set).
Please have a look at the Quick start guide, more specifically the Executing statements chapter. Right from that page:
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();
echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}
I feel like I'm missing something really simple here. Here's my sql query:
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
I then print the first result:
echo $row[0];
And get a correct value, the id of the first page (by page order):
10
So I submit a form which simply turns that $row[0] into $row[1].
And nothing prints. I don't understand.
You have to do this:
while ($row = mysqli_fetch_array($showpages, MYSQLI_NUM)) {
$id = $row[id];
// do something with the id
echo $id . "<br/>"; // Echo every id
}
This will iterate through all of the results
mysqli_fetch_array is a special function as each time you call it, it outputs the NEXT row.
So:
while ($row = mysqli_fetch_array(stuff)){
$var = $row['sql column'];
// In your case "$var = $row[0];" to get the id for the first row found.
}
is how you use it.
This will keep running the function until mysqli_fetch_array() eventually returns false. These each time it will output a new row. And the $row array is the array of one row in the sql table.
Use :
print_r($row);
in the while loop to see exactly what's being returned for use.
$getpages = "SELECT id FROM pages WHERE account = 2 ORDER BY page_order";
$showpages = #mysqli_query ($dbc, $getpages);
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
Question how many rows are fetched in this query in this case id, So MYSQL will result to 1 row affected, But since you are using
$row = mysqli_fetch_array($showpages, MYSQLI_NUM);
This code you used will not output anything try
$row[n] as n-1
$result->fetch_assoc() or mysqli_fetch_assoc($result)
catch one line at a time, from a mysqli_result:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
source: http://www.w3schools.com/php/php_mysql_select.asp
I want to select a row from mysql which matches a specific id. I want to get the result if the ID matches, if the ID does not exists in the database, it should not do anything.
I run sth like this:
$q = "SELECT * FROM entries where id= '1'";
$result = mysql_query($q) or die(mysql_error());
if($result){
$row = mysql_fetch_array($result) or die(mysql_error());
$name = $row['name'];
}
echo "hello".$name;
If the id '1' exists in the db, it should get the name, otherwise nothing or at least it should give the error, but when i use this, it just display no any content of the page which comes after this code. What I'm doing wrong?
If it does not display any code after this code, this is probably due to an error occuring and your error handling being set so the error is not displayed.
Try searching for the php error log file (normaly php_error.log) that should contain the error that you do not see.
Another thing i would try is adding more echo statements to see where exactly php stops interpreting.
Like this:
$q = "SELECT * FROM entries where id= '1'";
$result = mysql_query($q);
echo '<br />Query is send';
if(!$result) {
die('<br/>MySQL Error: ' . mysql_error());
}
else {
echo '<br />Result is true';
$row = mysql_fetch_array($result);
echo '<br />tryed fetching row';
if ($row === FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
die('<br/>MySQL Error: ' . mysql_error());
}
}
echo '<br />hello: "' . $name . '"';
That might help to get some more information about your problem.
$id = 1;
$sql = "SELECT `name` FROM `entries` WHERE `id` = $id LIMIT 1" //Since the id is probably an integer type on the DB, the single quotes aren't necessary, and sometimes screw it up. I think MySQL possibly thinks it's a string when in quotes.
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result))
{
$row = mysql_fetch_assoc($result) or die(mysql_error());
$name = $row['name'];
echo 'Hello ' . $name;
}
A SELECT query can return 0 rows if the condition you specified doesn't match any rows, and that isn't an error.
You should rather check the result of mysql_num_rows() after sending the query.
Maybe you should add a else statement to your if.
if($result)
....
else
do something
You might even want to do a try catch statement.