Retrieve certain row from array depending on a value - php

Echo out the right row from an array compiled from a mysql database.
I have extracted information from a database (locations) containing three fields: id, name, city into an array called $array. I want to loop through another database (events) in which the id's from the first database (locations) are stored in a field. When looped I want to display the corresponding name and city from the locations database.
Is this possible without having to fetch information every loop?
This is my first try
$query = "Select id, name, city FROM locations WHERE typ = '1'";
$result = mysqli_query($conn, $query);
$row = array();
while ($row = mysqli_fetch_assoc($result)) {
$array[] = $row;
}
And then I thought I could specify the key myself like this:
$query = "Select id, name, city FROM locations WHERE typ = '1'";
$result = mysqli_query($conn, $query);
$row = array();
while ($row = mysqli_fetch_assoc($result)) {
$array[$row['id']] = $row;
}
But I couldn't figure out how to echo the right row.

You can join both tables in a single query, using something like this:
Select locations.id, locations.name, locations.city, events.name
FROM locations
JOIN events ON locations.id = events.id
WHERE locations.typ = '1'
The events.id on the JOIN statement is assuming that this is the column name of the id in the events table. I also made the assumption that these are the two fields that will match between the two tables. Adjust accordingly if your matching criteria is different.
The SELECT statement was modified to pull columns from both tables. Add whichever fields are relevant to your needs.

Related

PHP Output data from 3 different tables

I'm trying to display a HTML table with information from 3 different tables in my mysql DB. However I am unsure on how to display the information from the third table.
Currently what I am using is:
$SQL = "SELECT members.*, exp.*, lvl.*
FROM members
INNER JOIN exp ON members.id = exp.member_id
INNER JOIN lvl ON members.id = lvl.member_id
ORDER BY lvl.level DESC,
lvl.total DESC, xp.total DESC";
$result = mysql_query($SQL) or die(mysql_error());
$count = 1;
while ($row = mysql_fetch_assoc($result)) {
$level = $row['level'];
$exp = $row['exp.overall'];
}
the $level is from the second table which grabs correctly, and the $exp is what I want to grab from the third table which is "exp" but it doesn't return anything
How can I change this because at the moment it just seems to be focusing on the data from the "lvl" table when using $row[]
Edit: Both the lvl and exp tables have a row in called 'overall' which is why using $row['overall'] doesn't return what I want as it returns the data from lvl table rather than exp.
First off I believe you have a typo in your last order column: should be exp.total DESC.
Secondly, unless you specify the columns to be named with dot notation explicitly they will retain their column names so try changing the last line to:
$exp = $row['overall'];.
Also consider using mysqli or PDO.

Getting Different ID Values in one table with DISTINCT query

My table in the DB
As you can see i have a table contain several IDs including Survey_survey ID and Store ID, i want to get all the Store IDs and their Survey_surveyIDs without duplicates.
Here is what i have tried
$getSurvey = mysqli_query($dbConnection , "SELECT DISTINCT Survey_surveyId FROM maintable");
while ($row = mysqli_fetch_array($getSurvey)) {
$getStoreIDS = mysqli_query($dbConnection , "SELECT DISTINCT Stores_storeID FROM maintable WHERE Survey_surveyId=".$row['Survey_surveyId']."");

How do I use Join in MySQLi php

I have databases called Over_Pics (with a table called "Pic" with Columns ID, PicID) and Over_SeenPics (with a table called "Seen" with Columns Text, PicID)
How do I correctly write the join function for this?
$r = mysqli_query($link, "SELECT Pic.PicID FROM Pic LEFT JOIN Seen ON Pic.PicID=Seen.PicID");
Also should the db name in mysqil_connect be left blank, since I need to access to dbs rather than 1?
I think you just need to specify the DB before the table names, like this:
$r = mysqli_query($link, "SELECT Over_Pics.Pic.PicID FROM Over_Pics.Pic LEFT JOIN Over_SeenPics.Seen ON Over_Pics.Pic.PicID=Over_SeenPics.Seen.PicID");
You can loop through the rows of the result set with this:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
foreach ($row as $key => $value){
echo $key." - ".$value.", ";
}
echo "\n";
}
That will output the results of the query to the screen. Of course you will most likely want to change the formatting.

Sorting the results of a mysql query

Im having difficulties trying to figure out an elegant solution to sorting the results of a mysql query based on a delimited string. Ill explain in more detail below
I am creating a database of contacts where individual users can add/remove people from a list. When the user adds a new contact I append the added contact id to a delimited string and store that data in a database column associated with that user (named contacts):
$userID = ?? //YOUR ID
$contactID = ?? //WHATEVER THE ADDED USER ID IS
$confirm = 0 //has the user been confirmed
$sql = "SELECT contacts FROM user WHERE id = '$userID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
$contact = $row['contacts'];
$contact .= '|'.$contactID.':'.$confirm;
$update = mysql_query("UPDATE user SET contacts = '$contact' WHERE id = '$userID'");
//contact column data might be: |10:0|18:0|36:0|5:0
When the user searches their contacts I grab the data from the contacts column, explode/split the string and return the individual users names:
$userID = ?? //YOUR ID
$sql = "SELECT contacts FROM user WHERE id = '$userID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
$contacts = explode("|", $row['contacts']);
foreach($contacts as $item)
{
list($contactID,$confirm) = split(":", $item);
$sql = "SELECT name FROM ".user." WHERE id = '$contactID'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
echo($row['name'].'<BR>');
}
This indeed does return all the names, but it returns them in the order of the delimited string. I cant seem to find an elegant way to sort by name alphabetically.
Should I not store the contacts list in a delimited string? How would you solve this?
You're right, you should not store the contacts in a string. Instead use another table which contains the user information. The new table should look something like the following:
Table: user_contacts
| user_id | contact_id | confirm |
-------------------------------------------
| your data here... |
Then when you need your contact list you can simply perform another query:
SELECT * FROM `user_contacts`
JOIN `users` ON `users`.`id` = `user_contatcs`.`user_id`
WHERE `users`.`id` = $id
ORDER BY `users`.`name`;
Or however you need to order it.
There are two obvious approaches:
Sort the results once you've fetched them
Fetch them all in one query and have the DB sort them
For #1, use usort():
$rows = array();
foreach ($contacts as $item){
list($contactID,$confirm) = split(":", $item);
$query = mysql_query("SELECT name FROM user WHERE id = '$contactID'");
$rows[] = mysql_fetch_array($query);
}
usort($rows, 'sort_by_name');
function sort_by_name($a, $b){
return strcmp($a['name'], $b['name']);
}
foreach ($rows as $row){
echo($row['name'].'<BR>');
}
For #2, build a list of IDs and use IN:
$ids = array();
foreach ($contacts as $item){
list($contactID,$confirm) = split(":", $item);
$ids[] = $contactID;
}
$ids = implode(',', $ids);
$query = mysql_query("SELECT name FROM user WHERE id IN ($ids) ORDER BY name ASC");
while ($row = mysql_fetch_array($query)){
echo($row['name'].'<BR>');
}
If you're using a relational database, then what you want is a separate table that stores person-contact relationships. Then you would modify your sql query to select based on a join across two tables
SELECT * FROM person, contact
JOIN contact ON person.id = contact.personid
JOIN person ON contact.contactid = person.id
WHERE person.id = $id
ORDER BY person.lastname
(That code is probably not quite correct.)
If you're using a no-sql type implementation, the way you're doing it is fine, except that you will either have to programmatically sort after the fact, or sort-on-insert. Sort on insert means you'd have to query the current list of contacts on inserting one, then sort through to find the right position and insert the id into the delimited string. Then save that back to the db. The downside to this is you'll only be able to sort one way.
Generally, people use relational databases and 'normalize' them as described above.

Efficiently maintaining order of a bullet point like list in mysql

I have a user editable list like bullet points. Points are being deleted and added(to the end or middle of the list) frequently. Is there any more efficient way of maintaining this list's ORDER than having each bullet have an id and keeping a SQL entry of the order split by commas? Example:
$result = mysql_query("SELECT order FROM users WHERE user = '$userId'"); //Get order for logged in user. returns id1,id2,id3,id4
$row = mysql_fetch_array($result);
$order = explode(',', $row['order']); //make the order an array
$result = mysql_query("SELECT id, data FROM bullets"); //get all the bullets
$bullets = array();
while($row = mysql_fetch_array($result)){
$project[$row['id']] = $row['data'];
}
Then run:
foreach($order as $k => $v){
echo '<li id="'.$k.'">'.$v.'</li>';
}
You can add an ordinal field to the bullets table.
Then your select looks like this:
SELECT id, data FROM bullets ORDER BY ordinal
Also, you shouldn't store denormalized data like you're doing with order in your users table.
Also, you shouldn't name a field order because it is a reserved word.

Categories