Printing result of mysql query from variable - php

So I wrote this earlier (in php), but everytime I try echo $test", I just get back resource id 5. Does anyone know how to actually print out the mysql query from the variable?
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)") or die(mysql_error());
print $dave;

This will print out the query:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
print $query;
This will print out the results:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($dave)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}

well you are returning an array of items from the database. so you need something like this.
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge,
SUM(total_order_amount) as test FROM `orders`
WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)")
or die(mysql_error());
while ($row = mysql_fetch_assoc($dave)) {
echo $row['order_date'];
echo $row['no_of_items'];
echo $row['shipping_charge'];
echo $row['test '];
}

From php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(),
and other functions for dealing with result tables, to access the
returned data.
http://php.net/manual/en/function.mysql-query.php

$sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1";
$records = mysql_query($sql);
you can change
LIMIT 1
to
LIMIT any number you want
This will show you the last INSERTED row first.

Related

How to mysqli_fetch_row while using mysqli_multi_query

I'm trying to get the latest info about some specific person, and I'm using a query like
SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID DESC LIMIT 1
and
SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID DESC LIMIT 1
because in the Table each day will insert new data for different person at the instant of updating it (for record reference), so I would like to print out a few persons latest info by "ORDER BY ID DESC LIMIT 1"
I have tried to print it out with "mysqli_multi_query" and "mysqli_fetch_row"
like
$con=mysqli_connect($localhost,$username,$password,'Table');
$sql = "SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID
DESC LIMIT 1 ";
$sql .= "SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID
DESC LIMIT 1";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
echo '<tr>'; // printing table row
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>'.$row[2].'</td>';
echo '<td>'.$row[3].'</td>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[5].'</td>';
echo '<td>'.$row[6].'</td>';
echo '<td>'.$row[7].'</td>';
echo '<td>'.$row[8].'</td>';
echo '<td>'.$row[9].'</td>';
echo '<td>'.$row[10].'</td>';
echo '<td>'.$row[11].'</td>';
echo '<td>'.$row[12].'</td>';
echo '<td>'.$row[13].'</td>';
echo '<td>'.$row[14].'</td>';
echo'</tr>'; // closing table row
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
In the result page , it doesn't show any error message , but no results are printed.
The individual queries were tested.
Please advise, much thanks
Is there another way to keep the query simple, so there is no need to use mysqli_multi_query?
Best practice indicates that you should always endeavor to make the fewest number of calls to the database for any task.
For this reason, a JOIN query is appropriate.
SELECT A.* FROM test A INNER JOIN (SELECT name, MAX(id) AS id FROM test GROUP BY name) B ON A.name=B.name AND A.id=B.id WHERE A.name IN ('Peter','Mary')
This will return the desired rows in one query in a single resultset which can then be iterated and displayed.
Here is an sqlfiddle demo: http://sqlfiddle.com/#!9/2ff063/3
P.s. Don't use LIKE when you are searching for non-variable values. I mean, only use it when _ or % are logically required.
This should work for you:
$con = mysqli_connect($localhost,$username,$password,'Table');
// Make a simple function
function personInfo($con, $sql)
{
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<table>
<tr>';
for($i=0; $i < count($row); $i++) echo '<td>'.$row[$i].'</td>';
echo '</tr>
</table>';
}
}
}
$sql1 = "SELECT * FROM Table WHERE Name='Peter' ORDER BY ID DESC LIMIT 1 ";
$sql2 = "SELECT * FROM Table WHERE Name='Mary' ORDER BY ID DESC LIMIT 1";
// Simply call the function
personInfo($con, $sql1);
personInfo($con, $sql2);

why this mysql query is not working?

Please help me regarding the specified problem:
The code section:
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='$_GET[id];'");
// the above query is not working
if ( mysql_num_rows($result) == 0 ) {
print "<p>No events right now.</p>\n";
}
else {
$lasteventmonth = '';
while ($row = mysql_fetch_array($result)) {
$eventmonth="";
$eventmonth = date("F Y",$row['eventdate']);
if ($lasteventmonth != $eventmonth) {
print "<p style='font-size: 18px;'><b>$eventmonth</b></p>";
}
$lasteventmonth = $eventmonth;
showEvent($row);
}
}
?>
........................
........................//other codes
when the code evaluates as follows:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Users\Fagun\Desktop\UsbWebserver\Root\mapcal\mapcal.php on line 122
No events right now.++++++++
After your call to mysql_query, use this:
if (! $result) {
echo mysql_errno() . ": " . mysql_error(). "\n";
}
this will tell you exactly, why MySQL won't run your query.
is ID a String or int? Either way I guess you shouldn't include a trailing semicolon?
Try changing it as follows...
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='$_GET[id]'");
I assume it's an issue with how you're using building the query and concatenating the id. Try this instead (notice how the ID is concatenated):
$query = "SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events
ORDER BY eventdate where
id='".$_GET[id]."'";
$result = mysql_query($query) or die(mysql_error());
You don't have to break it into 2 pieces, but - this should be easier to read and understand. You can even echo out the query before running it to see what query is actually being created, and try it manually on your database.
The or die(mysql_error()) part will give you specifics on what the issue is (if it wasn't the ID issue).
Quote values properly :
$_GET[id] should be $_GET['id']
Try below:
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='".$_GET['id']."');
Try this:
"SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='".$_GET['id'].";'"
I'm assuming that id does not come from user input. If it does, this is vulnerable to a SQL injection attack.
try:
$result = mysql_query("SELECT *,
UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate
FROM events
ORDER BY eventdate
where id= '" . intval($_GET['id']) . "'");
if($result)
{
//Do code
}
use intval() to make sure $_GET['id'] is an integer.
use the if statement to make sure the query has executed correctly.
Try this
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events where
id='".$_GET['id']."' ORDER BY eventdate");

Field from database not displaying in browser

Can anyone tell me why I am not getting the result of displaying the title on the browser when using the following script:
$sql =mysql_query( "SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 ");
echo $sql Title;
my connection is successful, but my desired result is not happening.
$sql = mysql_query( "SELECT * FROM `Tour` WHERE `Tour_No.`=1 LIMIT 0, 30 ");
while($row = mysql_fetch_object($sql))
{
echo $row->Title;
echo '<br />';
}
Maybe you can check this link for more example using mysql_query and mysql_fetch_object :
mysql_query: http://php.net/manual/en/function.mysql-query.php
mysql_fetch_object: http://www.php.net/manual/en/function.mysql-fetch-object.php
Your Query is invalid (single quotes are not used for tables / columns):
$result = mysql_query("SELECT Title FROM Tour WHERE Tour_No = 1 LIMIT 1");
You have to fetch the results:
$row = mysql_fetch_assoc($result);
Output the title:
echo $row['Title'];
Table and field names can be put in backtics, not in single quotes.
SELECT * FROM `Tour` WHERE `Tour_No.`=1 LIMIT 0, 30 // correct
SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 // wrong
if your getting 30 results you will need to loop through $sql, try the following.
$sql = mysql_query("SELECT * FROM `Tour` WHERE `Tour_No.` = 1 LIMIT 0, 30 ");
while($row = mysql_fetch_array($sql))
{
echo $row['Title'];
}
From http://php.net/mysql_query:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error....
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data."
Try this:
$sql =mysql_query( "SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 ");
$row = mysql_fetch_assoc($sql);
echo $row['Title'];
I'm not sure exactly what your columns are named, but that should get you on the right track.

mysql query written using php

$u_id=$event_assoc['Uniqueid'];
echo $u_id."\n";
$result1 = mysql_query("SELECT * FROM eventdetail WHERE unique_id = '$u_id'", $con1);
while($row = mysql_fetch_array($result1))
{
echo 'in eventdetail'."\n";
$e_id= $row['event_id'];
$destination= $row['destination'];
$uniqueid= $row['unique_id'];
$call_num= $row['channelid'];
}
echo mysql_num_rows($result1);
echo $e_id."\n";
echo $destination."\n";
echo $call_num."\n";
echo $uniqueid."\n";
if(mysql_num_rows($result1)>0)
{
echo 'calculate'."\n";
$result= mysql_query("SELECT sum(billsec)
FROM cdr
WHERE uniqueid = '$uniqueid'", $con2);
$bil = mysql_fetch_array($result);
$bill= (float) $bil['sum(billsec)'];
echo $bill."\n";
this is my code..
whenever i try to execute sum function query it retruns top row's billsec instead of addition of all row's billsec
You are doing a where on an unique ID in the sum query. Remove the where and it'll work
You are using unique id in your query.. And in a table single row will have that id, thats why you are getting top row's billsec... Remove the where clause in second query, and then check.
$result= mysql_query("SELECT sum(billsec)
FROM cdr
WHERE uniqueid = '$uniqueid'", $con2);
i guess there is a bug in this area...look again
The PHP statement for the SQL SUM Query should be:-
$result= mysql_query("SELECT sum(`billsec`), `uniqueid` FROM `cdr` GROUP BY `uniqueid` HAVING `uniqueid` = '$uniqueid'", $con2);
You need to use the clause "GROUP BY" whenever you are using any MySQL Aggregate functions (if needed). Also if you are using any aggregate functions (like "SUM", "MAX" etc), then you cannot use "WHERE" clause on the field (in this case, the field is "uniqueid") which is being used in the "GROUP BY" clause.
Hope it helps.

I am having problem in "fetching" only one entry from mysql

I want only one single data from that DB but I am not able to "take it out of" $res.
$sql = "SELECT * FROM `study_stuffs_extra`.`tid` ORDER BY `id` DESC LIMIT 1 ";
$res = query($sql);
$tid = $res['tid'];
I have also tried a while loop to do so, but "couldn't do it". Is there any other method to "do it"?
try
$sql = "SELECT * FROM `study_stuffs_extra`.`tid` ORDER BY `id` DESC LIMIT 1 ";
$res = mysql_query($sql);
$res=mysql_fetch_array($res);
$tid = $res['tid'];
SELECT tid FROM study_stuffs_extra ORDER BY `id` DESC LIMIT 1
Also, check what query returns. Is that a mysql result? the whole result set? a row? Do some print_r to see what you get. Check for db errors after executing queries.
You may need to subscript the first member of $res, assuming it is an array.
$firstRow = $res[0];

Categories