PHP - how to select from a table one query - php

I got a table that contains ID, Names, message, and time, I want to select from the table only one message query from each ID, Currently I select all the messages, this is my code
$query= mysql_query("SELECT * FROM `table` ORDER BY `time`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo '</br>';
echo $msg;
}
That Shows all messages ordered by time, Is there is a way to select only one message query from each ID?
Thanks,
Klaus

If you want only one message you can use LIMIT like this
SELECT * FROM table ORDER BY time LIMIT 1
Or if you want only one message from some id then you can use GROUP BY
SELECT * FROM table ORDER BY time GROUP BY id

Sure, pretty straightforward
This will fetch all messages given ID:
$id = 10 //Get your id in any way you need
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo $msg;
}
and this will fetch only the first message given ID
$id = 10
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id LIMIT 1")or die(mysql_error());
$row = mysql_fetch_array($query));
if($row){
$msg = $row['message'];
echo $msg;
}else{
echo 'no messages for id '.$id;
}

Related

How to display multiple fetched data?

I am using the following to fetch the latest articles from the database:
//Latest Article
$title_query1 = "SELECT title FROM articles ORDER BY id DESC LIMIT 1";
$description_query1 = "SELECT description FROM articles ORDER BY id DESC LIMIT 1";
$content_query1 = "SELECT content FROM articles ORDER BY id DESC LIMIT 1";
$image_query1 = "SELECT image FROM articles ORDER BY id DESC LIMIT 1";
$title_result1 = mysqli_query($con, $title_query1) or die(mysqli_error($con));
$description_result1 = mysqli_query($con, $description_query1) or die(mysqli_error($con));
$content_result1 = mysqli_query($con, $content_query1) or die(mysqli_error($con));
$image_result1 = mysqli_query($con, $image_query1) or die(mysqli_error($con));
//Second Latest Article
$title_query2 = "SELECT title FROM articles ORDER BY id DESC LIMIT 2,1";
$description_query2 = "SELECT description FROM articles ORDER BY id DESC LIMIT 2,1";
$content_query2 = "SELECT content FROM articles ORDER BY id DESC LIMIT 2,1";
$image_query2 = "SELECT image FROM articles ORDER BY id DESC LIMIT 2,1";
$title_result2 = mysqli_query($con, $title_query2) or die(mysqli_error($con));
$description_result2 = mysqli_query($con, $description_query2) or die(mysqli_error($con));
$content_result2 = mysqli_query($con, $content_query2) or die(mysqli_error($con));
$image_result2 = mysqli_query($con, $image_query2) or die(mysqli_error($con));
However, i'm not sure how I can then do something like this:
<h1>Here is the first article: <?php $title_result1 ?><h1>
<h2>Here is the first article description: <?php $description_result1 ?>
<h1>Here is the second article: <?php $title_result2 ?><h1>
<h2>Here is the second article description: <?php $description_result2 ?>
Also, is this method not good? If I am going to do this for 100+ articles, will it cause the web page to load slowly?
Thanks
You do not need to do a single query for each column. You can get all columns for a row by doing select * Also, as mentioned, you can fetch as many rows as you want, and loop through them.
I prefer the while method.. Example, show last 100 articles
// fetch latest 100
$sql = "SELECT * FROM articles ORDER BY id DESC LIMIT 100";
if ($result = mysqli_query($con, $sql)){
// got results, convert result object to array called $row
while ($row = mysqli_fetch_array($result)) {
// echo out $row array elements with
//the column names from the database as array index
echo '<h2>'. $row['title'] .'</h2>'; // example wrap results with HTML
echo '<b>' .$row['description'] .'</b>';
echo $row['content'];
echo <img src="'. $row['image'] .'" title="'.$row['description'].'">';
echo '<br>'; //so next result is on new line
} // end of while loop
} else {
//no result, error
}

in messaging system i don't know how to view message

i am new in php i want to know how to view message
this is my code
$idto = $_GET['id'];
$query2 = mysql_query("select * from users where id =".$idto." ");
$row2 = mysql_fetch_assoc($query2);
echo "<b><font size='6' face='Comic Sans MS'><center>".$row2['firstname']."</center></font></b><br><br>";
$query2 = mysql_query("select * from message where id_from =".$idto." and id_to =". $_SESSION['id']." ORDER BY id");
$query1 = mysql_query("select * from message where id_to =".$idto." and id_from =". $_SESSION['id']." ORDER BY id");
i select message send by user1 & by user 2 but i dont know how to view them correctly
when i use this
while ($row = mysql_fetch_assoc($query2) )
{
echo'<fieldset style="width:250" align="center">';
echo"<legend><b>".$row2['firstname']."</b></legend>";
echo $row['message'];
echo "<br>";
echo $row['date'];
echo"<hr>";
echo"</fieldset>";
}
while ($row1 = mysql_fetch_assoc($query1) )
{
echo'<fieldset style="width:250" align="center">';
echo"<legend><b>".$_SESSION['firstname']."</b></legend>";
echo $row1['message'];
echo "<br>";
echo $row1['date'];
echo"<hr>";
echo"</fieldset>";
}
it view messages but in incorrectly way
can any one help me please thanks :)
if you dont understand what i am saying
i mean i want to know how to view message
Firstly switch from mysql_* to mysqli_* because mysql_* functions are deprecated.
To order your queries in ascending order:
$query1 = mysql_query("
SELECT *
FROM message
WHERE id_to = ".$idto."
AND id_from = ".$_SESSION['id']."
ORDER BY id ASC
");
$query2 = mysql_query("
SELECT *
FROM message
WHERE id_from = ".$idto."
AND id_to = ".$_SESSION['id']."
ORDER BY id ASC
");

PHP - How to Use ORDER BY and GROUP BY together

I created a table that contains message, sender, to, time I want group by sender and order by time this is my code
$query= mysql_query("SELECT * FROM `table` ORDER BY `time` GROUP BY `sender`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr ['message'];
echo '</br>';
echo $msg;
}
that shows me this error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BYsender' at line 1
So how to fix that problem?
Thanks
Klaus
Note your precedence. After the results have been grouped , it should be ordered.
"SELECT * FROM `table` GROUP BY `sender` ORDER BY `time`"
try this code
$query= mysql_query("SELECT * FROM `table` GROUP BY `sender` ORDER BY `time` ")or die(mysql_error());
// ^^--will be before order
$num = mysql_num_rows($query); // out of the while loop
while($arr = mysql_fetch_array($query)){
$msg = $arr['message'].'<br />';
// ^^--remove space here
echo $msg;
}
how to use self-joins to get the max/min/something-n rows per group.
In your situation, it can be applied to the effect you want like so:
SELECT * FROM
(SELECT group_id, MAX(`yourdate`) AS yourdate FROM tbl_name GROUP BY group_id)
AS x JOIN tbl_name USING (`group_id`,yourdate);

How can I optimise this mysql/php query?

My page displays an image, and I want to display the previous and next image that is relevant to the current one. At the moment I run the same query 3x and modify the "where" statement with =, >, <.
It works but I feel there must be a better way to do this.
The image id's are not 1,2,3,4,5. and could be 1,2,10,20,21 etc. But if it is much more efficient I am willing to change this.
mysql_select_db("database", $conPro);
$currentid = mysql_real_escape_string($_GET['currentid']);
$query ="SELECT * FROM database WHERE id ='".$currentid."' LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$current_id = $row['id'];
$current_header = $row['title'];
$current_description =$row['desc'];
$current_image = "http://".$row['img'];
$current_url = "http://".$row['id']."/".$db_title."/";
$current_thumb = "http://".$row['cloud'];
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id <'".$currentid."' ORDER BY id DESC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$previous_id = $row['id'];
$previous_header = $row['title'];
$previous_description =$row['desc'];
$previous_image = "http://".$row['img'];
$previous_url = "http://".$row['id']."/".$db_title."/";
$previous_thumb = "http://".$row['cloud'];
}else{
$previous_none = "true"; //no rows found
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id >'".$currentid."' ORDER BY id ASC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$next_id = $row['id'];
$next_header = $row['title'];
$next_description =$row['desc'];
$next_image = "http://".$row['img'];
$next_url = "http://".$row['id']."/".$db_title."/";
$next_thumb = "http://".$row['cloud'];
}else{
$next_none = "true"; //no rows found
}
mysql_close($conPro);
Thank you for your time
You don't have to do select_db each time. Once you 'select' a db, it stays selected until you select something else.
You can't really get away from doing two separate queries to get the next/previous images, but you can fake it by using a union query:
(SELECT 'next' AS position, ...
FROM yourtable
WHERE (id > $currentid)
ORDER BY id ASC
LIMIT 1)
UNION
(SELECT 'prev' AS position, ...
FROM yourtable
WHERE (id < $currentid)
ORDER BY id DESC
LIMIT 1)
This would return two rows, containing a pseudofield named 'position' which will allow you to easily identify which row is the 'next' record, and which is the 'previous' one. Note that the brackets are required so that the 'order by' clauses apply to the individual queries. Without, mysql will take the order by clause from the last query in the union sequence and apply it to the full union results.
You can get the "previous" one first WHERE id <'".$currentid."' ORDER BY id DESC, and then query for two "above" it: SELECT * FROM database WHERE id >= '".$currentid."' ORDER BY id ASC then it takes only two queries instead of three.

Show all data in column

I am trying to show all of the data in the 'status' column of my table but am having troubles. What am I doing wrong:
<?php
$query1 = "SELECT id, status FROM alerts WHERE customerid='".$_SESSION['customerid']."' ORDER BY id LIMIT $start, $limit ";
$result = mysql_query($query1);
while ($row = mysql_fetch_array($result))
{
echo $row['status'] ;
}
?>
Try this:
$query1 = "SELECT id, `status` FROM alerts WHERE customerid='".$_SESSION['customerid']."' ORDER BY id LIMIT $start, $limit ";
$result = mysql_query($query1) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo $row['status'];
}
Also, make sure that:
$_SESSION['customerid'], $start and $limit are not empty. You can test the constructed query with echo $query1;
Note: Addition of mysql_error() in in the mysql_query will allow you to see if there is an error in the query.
I am trying to show all of the data in
the 'status' column of my table
If you want to show all the rows, your query should be:
$query1 = "SELECT id, `status` FROM alerts ORDER BY id";
But if you want to show for a specific customer, your query should be:
$query1 = "SELECT id, `status` FROM alerts WHERE customerid='".$_SESSION['customerid']."' ORDER BY id";

Categories