MySQL Query Return Thousands of Empty Results - php

When I run the second query to select departments it is returning my list of departments which is like 20 records, and then return thousands of blank enteries to the page freezes in a browser what did I do wrong?
mysql_select_db("ita", $con);
$results = mysql_query("SELECT * FROM `Colleges`");
$colleges = array();
while($row = mysql_fetch_assoc($results))
{
$colleges[] = array("Name" => $row['Name'], "Value" => $row['Value'], "ID" => $row['CollegeID']);
}
$collegecount = count($colleges);
$depts = array();
$result1 = mysql_query("SELECT * FROM `Departments` WHERE uid = `$uid`");
while($row = mysql_fetch_assoc($result1))
{
$depts = array("Name" => $row['Name'], "Value" => $row['Value'], "ID" => $row['CollegeID']);
}
$result = mysql_query("SELECT * FROM `users` WHERE wmuid = '$uid'");
while($row = mysql_fetch_assoc($result)){
//POPULATE FORM FIELDS FROM DB

You have backticks around your $uid. I'm not sure what exactly that will do since I doubt you have a column with the same name as whatevers in $uid, but it's probably going to cause some weird undefined behavior. Change your ` to ' Like:
SELECT * FROM `Departments` WHERE `uid` = '$uid'
Edit
Or if the column uid stores a numerical type remove the quotes altogether like:
SELECT * FROM `Departments` WHERE `uid` = $uid

Related

PHP MySQL Query with NOT LIKE specific id

I have 2 tables. The first one is messages and the second is room. msg_id from messages table is the same as id from room table. What I'm doing is selecting all msg_id and for each of them I wanna run a query that deletes all rooms that their ids dont match with msg_id:
My code:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
while($row = mysql_fetch_array( $result )) {
$me = $row[0]; //$me as a string
$int = (int)$me;//transform $me's value to int
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%" . $int . "%'");}
The $result2 query will delete all entries from room table, no matter the value of $int variable. That means that the check is not working. If I change the $result2 to this i.e.:
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%86%'");
all entries will be Deleted except the room entry with id = 86 (it works fine)
The basic plan is that I must keep all room entries that match their id with msg_id .
DELETE FROM `room` WHERE `id` NOT IN (SELECT `msg_id` FROM `messages`)
if you can't use subquery you can try:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
$ids = [];
while($row = mysql_fetch_array($result)) {
$ids[] = (int) $row[0];
}
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT IN (" . implode(',', $ids) . "));
and PLS don't USE mysql_query it is DEPRECATED
Could you use a subquery?
DELETE FROM ROOM WHERE id not in(SELECT msg_id FROM messages);
Try this query,
delete from 'room' where 'id' not in(select 'msg_id' from 'messages');
if it don't work for you, you can try NOT EQUAL TO query
delete from 'room' where 'id' <>(select 'msg_id' from 'messages');

How can I store this data in arrays

I have 3 tables users alerts and articles a user can setup an alert so when a new article is added that match his profile he will get an email
I am trying to write a small code to do this task
and this is what I came up with so far
$query_users = "SELECT * FROM `users`";
$result_users = $conn->query($query_users);
while ($users = mysqli_fetch_row($result_users)) {
$user_id = $users[0];
$user_email = $users[1];
$query_alerts = "SELECT * FROM `alerts` where user_id='$user_id' and active= '1' ";
$result_alerts = $conn->query($query_alerts);
while ($alerts = mysqli_fetch_row($result_alerts)) {
$category = mysqli_real_escape_string($conn,$alerts[2]);
$keyword = mysqli_real_escape_string($conn,$alerts[3]);
$query_search = "SELECT * FROM `articles` WHERE `category_id` = '$category' `title` LIKE '%$keyword%' ORDER BY `articles`.`id` ASC ";
$result_search = $conn->query($query_search);
$count = $result_search->num_rows;
}
}
Now what I want to do is to store the result this way
Put each alert category + keyword + count in an array then put it in an array that contain the user id and email
So at the bottom I can loop through the users and send to the user with id 1 and email example#website.com
a table like this
Category | Keyword | articles count
Health | Diet | 5
Buisness | Banks | 2
I hope you understood my idea, I am very confused and dizzy I didn't even know what to type in the search box
Take one array outside of while and add 3 variable in array when loop is executed.
i added 2 lines in your code which are.
$response = array();
and
$response[] = array
(
'category' => $category,
'keyword' => $keyword,
'count' => $count
);
Complete example
<?php
$query_users = "SELECT * FROM `users`";
$result_users = $conn->query($query_users);
$response = array();
while ($users = mysqli_fetch_row($result_users))
{
$user_id = $users[0];
$user_email = $users[1];
$query_alerts = "SELECT * FROM `alerts` where user_id='$user_id' and active= '1' ";
$result_alerts = $conn->query($query_alerts);
while ($alerts = mysqli_fetch_row($result_alerts))
{
$category = mysqli_real_escape_string($conn,$alerts[2]);
$keyword = mysqli_real_escape_string($conn,$alerts[3]);
$query_search = "SELECT * FROM `articles` WHERE `category_id` = '$category' `title` LIKE '%$keyword%' ORDER BY `articles`.`id` ASC ";
$result_search = $conn->query($query_search);
$count = $result_search->num_rows;
$response[] = array
(
'category' => $category,
'keyword' => $keyword,
'count' => $count
);
}
}
echo "<pre>";
print_r($response);

Add to array in comma separated values from database

my database table is named order. it has a row like order. I store values like this 1,2,3,4,5. Now i would like to add to array and from it out info..
I tried to do that but it is not working...
here is my code:
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
if want check print_r($array) Output
Array ( [0] => 1,23,4,5 )
this one is not working.. i think its supposed to be like this: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
FASTEST APPROACH
You need to use explode() function. Here is an example of it :
<?php
$array = array('0' =>'1,2,3,4,5');
$array = explode(',', $array[0]);
var_dump($array);
?>
Here is your updated code, to get array in that format.
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
$array = explode(',', $array[0]);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
Note this is solution which you are looking for. But it isn't recommended due to reason told to you as comment.
PROPER WAY TO HANDLE THIS
You should ideally normalize your Database so this kind of problem don't come even in future to you.
Here is a proposed table structure change, which you can consider, depending on your need & time.
Remove order column from your table. Add a new table named order_suborders as follows:
| COLUMN | TYPE |
|:-----------|------------:|
|parent_order| int |
| order_id | int |
You can change name of columns and table according to your wish.
Move old data accordingly.
Use query SELECT order_suborders.order_id FROM order, order_suborders WHERE order.id = ".$_GET['id']." AND order.id = order_suborders.parent_order
you can use explod to split with ","
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
//$array = array($sql_order);
$array=explod(",",$sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}

I want to put a while loop into an array

I have a multidimensional array where under "images" I want to loop 4 rows from my database. It means I am trying to put a loop into an array. Help me.
$sql_album = "SELECT * FROM albums";
$res_album = mysql_query($sql_album) or die(mysql_error());
$albums = array();
while ($row_album = mysql_fetch_assoc($res_album)) {
$albums[$row_album['title']] = array(
"description" => $row_album['description'],
"date" => $row_album['date'],
"images" => array(
//i want to insert a loop here shown down
)
);
}
This is the loop i want to insert where i wrote the comment in the upper script:
$sql_thumb = "SELECT * FROM photos WHERE album_id = '".$row_album['id']."' LIMIT 0, 4";
$res_thumb = mysql_query($sql_thumb) or die(mysql_error());
while ($row_thumb = mysql_fetch_assoc($res_thumb)) {
echo $row_thumb['thumb_url'];
}
Start here...
include('../path/to/mysqli/connection/statements');
$query = "
SELECT a.id
, a.title
, a.description
, a.date
, p.thumb_url
FROM albums a
LEFT
JOIN photos p
ON p.album_id = a.id
ORDER
BY a.id;
";
$result = mysqli_fetch_assoc($db,$query);
Sadly PHP does not allow this kind of usage. You could however do something like this
$sql_album = "SELECT * FROM albums";
$res_album = mysql_query($sql_album) or die(mysql_error());
$albums = array();
while ($row_album = mysql_fetch_assoc($res_album)) {
$albums[$row_album['title']] = array(
"description" => $row_album['description'],
"date" => $row_album['date'],
"images" => array()
);
$sql_thumb = "SELECT * FROM photos WHERE album_id = '".$row_album['id']."' LIMIT 0, 4";
$res_thumb = mysql_query($sql_thumb) or die(mysql_error());
while ($row_thumb = mysql_fetch_assoc($res_thumb)) {
$albums[$row_album['title']]["images"][] = row_thumb['thumb_url'];
}
}

Group By 2 Columns with similar info to link with a 2nd table

I have two columns with similar info:
column 1 = item 1, item 3, item 5
column 3 = item 3, item 5, item 8
I want to display how many of each item are in total from both columns.
I have this:
$sql = mysql_query("SELECT FirstTypeID, SecondTypeID, ThirdTypeID, DesignID, COUNT(DesignID) FROM designs WHERE Approved = '1' GROUP BY FirstTypeID, SecondTypeID, ThirdTypeID");
while ($row = mysql_fetch_array($sql)) {
$DesignID = stripslashes($row['DesignID']);
$FirstTypeID = stripslashes($row['FirstTypeID']);
$SecondTypeID = stripslashes($row['SecondTypeID']);
$ThirdTypeID = stripslashes($row['ThirdTypeID']);
$Total = stripslashes($row['COUNT(DesignID)']);
}
$result2 = mysql_query("SELECT * FROM types WHERE TypeID = '$FirstTypeID' OR TypeID = '$SecondTypeID' OR TypeID = '$ThirdTypeID'");
while ($row2 = mysql_fetch_array($result2)) {
echo "<li><a href='index_type.php?TypeID=".$row2{'TypeID'}."'>".$row2{'TypeName'}." (" . $Total . ")</a></li>";
}
but I'm not getting the result that I want, it's only giving me results from one column.
I'm not sure if this is what you are asking for but well here it is
$typesIDs = array(type0 => "", type1 => "", type2 => ""...);
foreach($typesID as $index=>$value){
$query = "SELECT COUNT(*) AS total FROM designs COLUMN1 = ".$index." OR COLUMN2 = ".$index;
$sql = mysql_query($query);
$row = mysql_fetch_array($sql);
array[$index] => $row["total"]
}

Categories