How to properly optimise mysql select statement - php

I have a web page that is divided into different sections. Each section has to show different results. These results are gotten from the database.
This is a sample data on SQLfiddle
http://sqlfiddle.com/#!9/ad98b/1
The following code is what comes to my mind but I'm afraid that it might somehow overload the server when this page is accessed multiple times by different people
$sectionA = $connect->query("SELECT * FROM Main_Section WHERE section = `A`
");
while ($row = $sectionA->fetch_array(MYSQLI_BOTH))
{
$id = $row["id"];
$name = $row["name"];
$sec_result_a = $sec_result_a.'<p>'.$id.'</p><h3>'.$name.'</h3>';
}
$sectionB = $connect->query("SELECT * FROM Main_Section WHERE section = `B` ");
while ($row = $sectionB->fetch_array(MYSQLI_BOTH))
{
$id = $row["id"];
$name = $row["name"];
$sec_result_b = $sec_result_b.'<p>'.$id.'</p><h3>'.$name.'</h3>';
}
$sectionC = $connect->query("SELECT * FROM Main_Section WHERE section = `C` ");
while ($row = $sectionC->fetch_array(MYSQLI_BOTH))
{
$id = $row["id"];
$name = $row["name"];
$sec_result_c= $sec_result_c.'<p>'.$id.'</p><h3>'.$name.'</h3>';
}
UP TO section Z
Is there a way I can Optimise this properly?

Unless there's more to the picture, why not just query everything, ordered by section, to have the A-Z:
SELECT * FROM Main_Section ORDER BY section
... and then process the results with one loop, which could look something like this:
$sections = $connect->query("SELECT * FROM Main_Section ORDER BY section");
while ($row = $sections->fetch_array())
{
echo $row['section'] . ' ' . '<p>' . $row['id'] . '</p><h3>' . $row['firstname'] . ' ' . $row['lastname'] . '</h3>';
}

Related

SQL statement only runs when page is refreshed, not on initial view

So I have attached a few view counters to pages on my website, and one of the just will not work. It only updates the attribute 'views' when the page is refreshed, not on the initial load for the user. This is of course a problem because I cannot track page views if the user must refresh each time they view an album.
Here is my code:
$sql = "SELECT * FROM albums WHERE path='" . $albumPath . "'";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$albumName = $row['name'];
$views = $row['views'];
$id = $row['id'];
}
$views = intval($views) + 1;
$sql = "UPDATE albums SET views='9' WHERE id='" . $id . "'";
$result = mysql_query($result);
Thank you for the help.
Looks like your last line should be $result = mysql_query($sql); instead of mysql_query($result). Also, on your second to last line, don't you mean to set views equal to $views instead of 9?
$sql = "SELECT * FROM albums WHERE path='" . $albumPath . "'";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$albumName = $row['name'];
$views = $row['views'];
$id = $row['id'];
}
$views = intval($views) + 1;
$sql = "UPDATE albums SET views='$views' WHERE id='" . $id . "'";
$result = mysql_query($sql);

Php Mysql SELECT query 1 column equals 1 variable

I've been throw so many threads for 4+ hours here and abroad and seem to be missing a simple thing.
I'm trying to have several users upload their 'news' to MYSQL.
Yet I want to display only the 'news' with the logged in username (userpost) attached to the row.
$current is the username for who is logged in, which works.
Example A isn't filtering out rows that don't contain the $current user.
Example B isn't providing any output
So I've tried both A:
$result = mysqli_query($con,"SELECT * FROM images_tbl");
//echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
if ($row['userpost'] = '.$current.') {
$num = 0;
$num = $num + 1;
$pic.$num = $row['images_path'];
$h1 = $row['hlone'];
and B:
$result = mysqli_query($con,"SELECT * FROM images_tbl WHERE (userpost = '.$current.')");
echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
echo $row['hlone'] . " " . $row['images_path'];
echo "<img src=\"" .$row['images_path']. "\">";
}
27, images/08-10-2014-1412752801.jpg(images_path), 2014-10-08, Headline(hlone), Headline2, story, testb(userpost)
Any help would be greatly appreciated.
Add where clause to your query
//in situation A
$result = mysqli_query($con,"SELECT * FROM images_tbl where username='".$current."'");
//username is column name for user you might have to change this
while($row = mysqli_fetch_array($result)) {
echo $row['images_path'];
echo $row['hlone'];
}
In situation B try this
$result = mysqli_query($con,"SELECT * FROM images_tbl WHERE userpost = '".$current."')");
echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
echo $row['hlone'] . " " . $row['images_path'];
echo "<img src=\"" .$row['images_path']. "\">";
}
Why are you trying to filter with PHP.
If you want to filter the 'news' that have not written by current user just use MySQL Where clause:
// For Example A
$result = mysqli_query($con, "SELECT * FROM images_tbl WHERE userpost != '{$current}'");
while($row = mysqli_fetch_array($result)) {
$pic = $row['images_path'];
$h1 = $row['hlone'];
}
// For Example B
$result = mysqli_query($con,"SELECT * FROM images_tbl WHERE userpost = '{$current}')");
echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
echo $row['hlone'] . " " . $row['images_path'];
echo "<img src=\"" .$row['images_path']. "\">";
}
It's easy with MySQL's filtering options. You should do more research about MySQL.

My while loop from database is repeating results. I know it's my poorly formatted query.

I have a query to bring results from my database. It works... until there are more than 2 results that it, then it just repeats some results before adding in new ones.
I know it will be because my query is fairly poor, can anyone advise me?
The idea is
connect to database with photo links
get the default user picture as $profile_main
join the words "photo_" with the default picture number and call it
$answer (ex: column 'photo_1' in database)
now check the database again and get the results for $answer and
output all information from that database column.
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$profile_main = $row['default'];
$answer = "photo_" . $profile_main;
$result2 = mysqli_query($con,"SELECT $answer FROM tbl_photos");
while($row = mysqli_fetch_array($result2))
{
echo "<img src=\"" . $row[0] . "\">";
}
}
mysql_fetch_row returns numerical indexes instead of column names (so ['default'] just won't work)...
This is how I would do it if I'm understanding you correctly:
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_assoc($result))
{
$answer = $row['photo_'.$row['default']];
echo "<img src=\"" . $answer . "\">";
}
Anyway, this is assuming default and photo_x are in the same row.
If you want only one result for a photo then you can use LIMIT like this
SELECT $answer FROM tbl_photos LIMIT 1
First, both loops you set same $row variable. Use 2 different variable names so that the results don't get mixed up.
Second issue is that you have you have 2 loops , so it will show all results each time. You need to break in the second loop. Like this:
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$profile_main = $row['default'];
$answer = "photo_" . $profile_main;
$result2 = mysqli_query($con,"SELECT $answer FROM tbl_photos");
while($row2 = mysqli_fetch_array($result2))
{
echo "<img src=\"" . $row2[0] . "\">";
break;
}
}
Or by using only one query, it would be much more efficient:
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$profile_main = $row['default'];
$answer = "photo_" . $profile_main;
echo "<img src=\"" . $row[$answer] . "\">";
}
You only require 1 query.
TRY
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$photo = "photo_" .($row['default'];
echo "<img src=\"" . $photo . "\">";
}

"No data received" on GET request

I keep getting a "No data received" error, I know this is common with Google Chrome so I tried in IE and I get a connection problem error. Here is my script, I really don't see what is causing this error.
$getAlName = mysql_query("SELECT * FROM categories WHERE id=" . $cat);
$alName = mysql_feth_assoc($getAlName);
$images = mysql_query("SELECT * FROM images WHERE category=" . $alName['name']);
while($imgs = mysql_fetch_object($images)) {
$url = $imgs->url;
$id = $imgs->id;
echo ("<img src='" . $url . "'></img>\n");
}
You need to add single quotes around your strings:
"SELECT * FROM images WHERE category = '" . $alName['name']) . "'";
...and you also got a typo, use mysql_fetch_assoc instead of mysql_feth_assoc($getAlName);
//Make a subquery and you'll thank yourself later:
$q = "SELECT URL, ID FROM images WHERE category IN ".
"( SELECT * FROM categories WHERE id=" . $cat . ")";
echo $q; // just to test. no data received probably has to do with no output to
// the browser. This will output to the browser.
$images = mysql_query($q);
// this is the same.
while($imgs = mysql_fetch_object($images)) {
$url = $imgs->url;
$id = $imgs->id;
echo ("<img src='" . $url . "'></img>\n");
}

How can I make this simple block shorter and better?

I'm using the following not well thought code block to retrieve categories and it's topics.
$query1 = "SELECT * from categories";
$result = mysql_query($query1);
while ($out = mysql_fetch_assoc($result)){
//category
print '<h2>' . $out['name'] . '</h2>';
$query2 = "SELECT * from topics where fkid = $out[id]";
$result2 = mysql_query($query2);
while($top = mysql_fetch_assoc($result2)){
//topic
print $top['name'] . '<br>';
}
}
The above does the trick. I know this is not the most practical and this being the reason I ask the group.
How can I better this so it's more practical and simple?
A classical case for a JOIN:
SELECT * FROM categories JOIN topics ON categories.id = topic.fkid ORDER BY categories.name;
Then to print, we only print the header if it has changed (thanks, Rajasur!):
$catname = "";
while ($out = mysql_fetch_assoc($result))
{
if ($out["name"] != $catname) // maybe need strcmp here
{
$catname = $out["name"];
print($catname)
}
/* print the rest */
}
Just use a single query that joins the two tables.
$query = "SELECT categories.name AS category_name, topics.name AS topic_name
FROM categories JOIN topics ON categories.id = topics.fkid
ORDER BY categories.name ASC, topics.name ASC";
$resultSet = mysql_query($query);
$currentCategory = "";
while ($cRecord = mysql_fetch_assoc($resultSet)) {
if ($currentCategory != $cRecord['category_name']) {
$currentCategory = $cRecord['category_name'];
echo "<h2>" . $currentCategory . "</h2>";
}
echo $cRecord['topic_name'] . "<br/>";
}
mysql_close($resultSet);

Categories