PHP SQL query id from table with multiple values in rows - php

I'm having an issue querying multiple values from rows that have a certain value. I use the SQL code below to grab column "group_id"'s values if the "id" equals 999. In the "xx_groupmap" table, the id 999 shows up three times with different values. Below is my table.
table xx_groupmap
-------------------
id | group_id
-------------------
999 | 2
999 | 7
999 | 8
Below is the code I use
$db = JFactory::getDbo();
$query = "SELECT group_id FROM xx_groupmap WHERE id = '999'";
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ($results as $t) {
}
So in the end when I want to return the three values of id 999 I use this code
echo $t->group_id;
but it only outputs one number. How do I build an array with the three values from id 999?

Thats because, when you are in the foreach, $t is always updated, and you will get tha last $t only. Put them into an array.
$ids = array();
foreach ($results as $t) {
$ids[] = $t->group_id;
}
var_dump($ids);

Related

looping through rows of a mysql table with non sequential index

I have a MySQL table that looks like this
index (auto incremented)
data
type
1
a1
1
3
a2
1
4
b62
3
9
m52
1
and i loop through it with this code
for($i=1; $i<= number of rows; $i++){
$query = "SELECT * FROM messagesforinstructor where type='1' and index='$i'";
$result = mysqli_query($db, $query);
$display=mysqli_fetch_assoc($result);
echo $display['data'];
}
but as you can see that it would fail cause the auto incremented indexes are not sequential.so at i=2 it would fail without making it to i=3.
any idea how to make it select the next index in the table
Simple solution
Don't use * use specified column names
Use one query to retrieve the entire result set
Use OOP approach and save yourself having to repeat code (you don't neeed to change the connection but you can:
// From...
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
// To...
$db = new mysqli($db_host,$db_user,$db_pass,$db_name)
I assume that type is an integer field; no need to use quotation marks in the query
Code
// Run the query to select the messages
$sql = "SELECT data FROM messagesforinstructor WHERE type = 1";
$query = $db->query($sql);
// Option 1
// Loop though result set with a foreach loop
foreach ($query as $message) {
echo $message[0];
}
// Option 2
// Loop through the result set with a while loop
while ($message = $query->fetch_assoc()) {
echo $message["data"];
}

Updating a database column (vertically) with an array

I have a database table with the following structure. id column is added later. So all id cells are empty.
id | song | album | artist
-----------------------------
| song1 | alb1 | art1
| song2 | alb2 | art2
| song3 | alb3 | art3
| song4 | alb4 | art4
| song5 | alb5 | art5
I have an array which holds the id values for the table. I'll be updating the table (the id column) with the values in the array. For example:
$array = [
"C45Rm3fLGn",
"ocIik81up2",
"IcuSn9T77y",
"tJv7AbF53r",
"a9eZ6xYM5Y",
];
These items are unique random strings.
How should I proceed? I'm thinking about iterating the array and using UPDATE on each item.
$array = [
"C45Rm3fLGn",
"ocIik81up2",
"IcuSn9T77y",
"tJv7AbF53r",
"a9eZ6xYM5Y",
];
$rows = $mysqli->query("SELECT * FROM songs")->fetch_all(MYSQLI_ASSOC);
for ($i = 0; $i < count($array); $i++) {
$row = $rows[$i];
$id = $array[$i];
$mysqli->query("UPDATE songs SET id = '$id' WHERE song = '{$row["song"]}' AND artist = '{$row["artist"]}'");
}
Is there a more preferable way?
UPDATE: I do not use auto increment and the id column didn't exist at the time of table was created. Now, I've added an id column. There are 300+ records. IDs of the records are unique random strings. Before I add another record to the database, every record needs to have a unique random string for its id, so that when I insert a new record, I can create a random string and check if it's unique or not by comparing it to the ids in the table.
At this stage, I just need to update the id column using an array. Array items are irrelevant.
Prepared statements are designed to be prepared once and executed many times, with a minimum of overhead. Using them is also an absolute necessity if the data you're inserting is user-generated.
It's been a long time since I've done anything with MySQLi (I strongly recommend looking at PDO for much simpler code) but this should work:
$array = [
"C45Rm3fLGn",
"ocIik81up2",
"IcuSn9T77y",
"tJv7AbF53r",
"a9eZ6xYM5Y",
];
$rows = $mysqli->query("SELECT * FROM songs")->fetch_all(MYSQLI_ASSOC);
$stmt = $mysqli->prepare("UPDATE songs SET id=? WHERE song=? AND artist=?");
foreach ($array as $i=>$id) {
$row = $rows[$i];
$stmt->bind_param("sss", $id, $row["song"], $row["artist"]);
$stmt->execute();
}
I would also recommend building your array such that it references the columns you're renaming. You're relying on both the database and the array being in the same order, which may not always be the case.
Please try this query:
UPDATE `myTable` SET `id`= CONCAT(item-name, "-id");
Or you can set a counter like this:
UPDATE `myTable`, (SELECT #i := 0) c SET `id`= CONCAT(item-name, "-id-", #i:=#i+1)
I hope this will help you.

PHP-MySQL: Returning Query as Array index name and value

I have a MySQL table like this:
------------
|animal|legs|
------------
| cat 4 |
| chicken 2 |
Is it possible to return an array in PHP with animals as its index name and legs as its values without fetching one by one as in mysqli_fetch_all ?
$result[cat]=4
$result[chicken]=2.
I tried
$q = mysqli_fetch_all($q);
$array=array_combine($q2[0], $q2[1]);
but it does not give me the output that I wanted.
Using safeMysql
$dic = $db->getIndCol("animal","SELECT * FROM animals");
Try:
$result = array();
while ($row = mysqli_fetch_all($q, MYSQLI_ASSOC)){
$result[$row['animal']] = $row['legs'];
}
Remember to use apostrophes around strings in array labels in this way, as 'cat' or 'chicken'.

php simple following-follower system, removing a value from array and updating with foreach (updating doesn't work)

I made a simple following-follower system with php(pdo) and mysql. My problem is,
Let's say there is a user name Mike with ID number 99. And Mike has two followers, Greg(id = 77) and Jenny(id = 88)
Greg's following list looks like this (1,2,3,4,99), and Jenny's following list looks like this (5,6,99,7)
What I am trying to do is, when Mike(99) deletes his account, I want to remove id number 99 from Greg(77) and Jenny(88)'s following lists.
Table called 'mytable' has 3 fields. id(INT), following_list(text), follower_list(text).
I've been struggling with this problem for a few days. Can anyone please give me some advice? Thank you so much in advance!!!
Below is my update function
public function update_following_list(){
// $this->myid is Mike's id number(99) who is about to delete his account
// Selecting the list of people following Mike
$query = "SELECT 'follower_list' FROM 'mytable' WHERE 'id' = $this->myid";
$result = $this->dbc->query($query);
foreach($result as $row){
$this->follower_list = $row['follower_list'];
// When I echo $this->follower_list, I get 77,88
// Now querying Greg(77) and Jenny(88)'s following_lists, which have Mike's id number(99) in them.
$query = "SELECT 'following_list' FROM 'mytable' WHERE 'id' IN ($this->follower_list)";
$result = $this->dbc->query($query);
foreach($result as $row){
$this->following_list = $row['following_list'];
// When I echo $this->following_list, I get both Greg(1,2,3,4,99) and Jenny(5,6,99,7)'s following lists
// Here, I am turning following list into array by using explode
$this->following_array = explode(",", $this->following_list);
foreach($this->following_array as $key => $value){
if($value == $this->myid){
// Removing Mike(99)'s id number from Greg and Jenny's following lists
unset($this->following_array[$key]);
// Add back commas, which will then become string
$this->new_following_list = implode(",", $this->_following_array);
// When I echo $this->new_following_list, I get both Greg(1,2,3,4) and Jenny(5,6,7)'s new list without Mike(99)'s id number
// My problem starts here. I was able to remove Mike's id number from Greg and Jenny's lists. But I am having a trouble updating Greg and Jenny's following lists with new following lists.
// The update query below does not work...
$query = "UPDATE 'mytable' SET 'following_list' = $this->new_following_list WHERE 'id' IN ($this->follower_list)";
$result = $this->dbc->query($query);
} // End of if($value == $this->myid)
} // End of foreach($this->following_array as $key => $value)
}
}
} // End of function
This will not scale properly. It's better to normalize your data model like this:
following
user_id | following_user_id
---------------------------
77 | 1
77 | 2
77 | 3
77 | 4
77 | 99
88 | 5
88 | 6
88 | 7
88 | 99
And add two indexes:
UNIQUE(user_id, following_user_id)
INDEX(following_user_id)
To get followers of 99:
SELECT * FROM following WHERE following_user_id=99;
To see who 77 follows:
SELECT * FROM following WHERE user_id=77;
I think your database setup is not optimal. Store comma-separated values in one field, screams for a binding table and some normalization !!
You should have your comma separated value list to be a table/relation, e.g.:
followTable:/ user_id | follows
Deletion of mike's id is then as simple as:
DELETE FROM followTable WHERE follows = 99 OR user_id = 99
The latter makes sure the links between Mike and his followers are being deleted also.

checkbox mysql/php output. How do I check ID's between 2 tables?

I have 2 tables, one with a infinite list of Names and IDs.
The first is the list of Names and their ID.
NameID ~ Name
1 Bob
2 Jon
3 Peter
4 Simon
The second table I have is a list of ID's in a linking table, so I can associate what name's belong to a House, for example.
NameID ~ HouseID
1 1
2 2
3 3
4 4
I am outputting the Names as checkboxes in a while-loop, and inserting them into my database with no problems with a foreach loop.
The problem I am facing is checking Names and Houses against each other. I want to check the checkbox if the ID exists in Houses. i.e with a simple variable if.
if ($intNameID = $xxx) { $checked = 'checked="checked"'; } else { $checked = ''; }
The problem I am facing is understanding how I can deal with these two tables, where Names is currently in a while-loop. I've tried selecting my Houses ID's with a sql statement, but stumped how I can check what ID's have been added to my linking table....
Any help with semantics or example code is appreciated.
Here is your code rewritten so that it works, with some more sensible variable names, and a few unnecessary variables removed:
<?php
$query1 = "SELECT projectTemplateID, projectID
FROM projectTempList
WHERE projectID = '$intProjectID'";
$result1 = mysql_query($query1);
$arrProjectTemplateIDCheck = array();
while ($row = mysql_fetch_assoc($result1)) {
$arrProjectTemplateIDCheck[] = $row['projectTemplateID'];
}
$query2 = "SELECT projectTempID, projectTempName
FROM projectTemplates";
$result2 = mysql_query($query2);
while ($row = mysql_fetch_assoc($result)){
$checked = (in_array($row['projectTempID'],$arrProjectTemplateIDCheck)) ? ' checked="checked"' : '';
echo '<input type="checkbox" name="recharge_costs[]" value="'.$row['projectTempID'].'"'.$checked.' /> '.$row['projectTempName']." <br />\n";
}

Categories