Save MySQL results in 2D array - php - php

I'm trying to fetch the result of a query to my database. I have no problems doing so when the resultset is just 1 row, but when it's multiple rows I only get the first one.
Here is my db:
-----keys-------------------
| id | key_nbr | date |
----------------------------
| 42 | abc123 | xxxx |
| 49 | 789xyz | wxyz |
----------------------------
My function:
function get_key_info($mysqli) {
if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
if ($stmt = $mysqli->query("SELECT id, key_nbr, date FROM keys WHERE id=$user_id")){
$row = $stmt->fetch_array(MYSQLI_ASSOC);
return $row;
}
}
return null;
}
Output when doing print_r($row); is only the first row:
Array ( [id] => 42 [key_nbr] => abc123 [date] => xxxx) How to make it print all rows?

You have to check for total number of rows before fetching the data, if it's not zero then execute the loop and fetch all records.
function get_key_info($mysqli) {
if (isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
if ($stmt = $mysqli->query("SELECT id, key_nbr, date FROM keys WHERE id=$user_id")){
if($stmt->num_rows != 0) {
$row = array();
while($r = $stmt->fetch_array(MYSQLI_ASSOC)) {
$row[] = $r;
}
return $row;
}
}
}
return null;
}

Related

How to select and assign to a specific $key, a specific $value, among multiple choices?

I have a MySQL table with multiple columns, from which I need to select all of them of each record, and to create a specific $key=>$value from it.
for example
TABLE
ID | group_cat | group_sec | group_name | enabled | sent
-------------------------------------------------------------------------------------
1 | C | sct_a | Project_A | 1 | no
2 | C | sct_b | Project_B | 1 | no
3 | P | sct_c | Moderators | 1 | no
4 | C | sct_d | Ambassad | 1 | no
5 | P | sct_e | PMP | 0 | no
The MySQL query I need is "SELECT * FROM groups WHERE sent = 'no' "
By PHP is
PHP Code
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $key => $value) { $$key = $value; }
...
...
...
}
Here my question:
I need that the $key is from the column 'group_sec' and the related $value is from the column 'group_name'. So that the couple $$key=>$value can return this result (for instance)
echo $sec_b;
returns: Project_B
Could you help me to get this done please?
Thank you in advance
This will do the job for you:
${$row['group_sec']} = $row['group_name'];
echo $sct_b;
Output:
Project_B
You would use this in your while loop (the foreach can probably be deleted):
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
${$row['group_sec']} = $row['group_name'];
...
// do something with $sct_b
...
}
Alternatively, if your column names might change, but the positions will stay the same, you can use
while($row = $sth->fetch(PDO::FETCH_NUM)) {
${$row[2]} = $row[3];
...
// do something with $sct_b
...
}
You can build an array based on key and value you prefer using $row['group_sec'] for key and $row['group_name'] eg:
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$myArray[$row['group_sec']] = $row['group_name'];
}
and you can see the result
foreach($myArray as $key => $value){
echo $key . ' - ' . $value . '<br>';
}
$sql = "SELECT * FROM groups WHERE sent= 'no'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$list=[];
while($row = $result->fetch_assoc()) {
$list{$row['group_sec']} = $row['group_name'];
}
}

Fetch Mysql Results into serialized data

I have this table:
| id | related_id |
| 1 | 100 |
| 1 | 200 |
| 1 | 300 |
| 2 | 400 |
| 2 | 500 |
| 2 | 600 |
I need to retrieve serialized data as:
a:3:{i:1;s:3:"100";i:2;s:3:"200";i:3;s:3:"300";}
Query
SELECT id, related_id from mytable where id = 1;
I'm trying to get this using 'while'
$result = $link->query($query);
$item = array();
while($f = $result->fetch_assoc()){
$id = $f['id'];
if ($id == $f['id']){
$item[] = $f['related_id'];
}
print serialize($item);
break; // for test
}
SOLUTION that works for me (provided by Erwin - Thanks!)
$item = array();
while($f = $result->fetch_assoc()) {
$id = $f['id'];
if (!array_key_exists($id, $item)) {
$item[$id] = [1 => $f['related_id']];
} else {
$item[$id][] = $f['related_id'];
}
}
foreach ($item as $value) {
print serialize($value) . PHP_EOL;
}
Collect first each related_id and store to id array with your while loop. Then print each using foreach.
$item = array();
while($f = $result->fetch_assoc()) {
$id = $f['id'];
if (!array_key_exists($id, $item)) { // create id array if not exist
$item[$id] = [1 => $f['related_id']]; // To start with index 1
} else {
$item[$id][] = $f['related_id']; // Push each new related_id
}
}
foreach ($item as $value) {
print serialize($value); // Print each serialized
echo '<br>'; // New line
}
What you are trying to do is something like this:
$result = $link->query($query);
$items = array();
while($f = $result->fetch_assoc()){
$id = $f['id'];
if(!isset($items[$id])) {
$items[$id] = array();
}
$items[$id][] = $f['related_id'];
}
foreach($items as $item) {
print serialize($item);
}
For your serialized string, you have to work with an array with related_id in the second layer. The first layer is to save all related_id in an array with the same id.
You have 6 rows, 3 have id 1 and 3 have id 2. You are specifying that you want to use these ids as array keys so you will end up with 2 arrays, each holding 3 values.
If you want each row in its own array you do this:
while($f = $result->fetch_assoc()){
$item[] = array($f['id'] => $f['related_id']);
}

php mysql match value from multiple values a column

I want to find a value from a column which has multiple values like (23,24,25), Using php mysqli query.
Table:
+-----------------+
id | tag_ids |
+-----------------+
1 | 3,4,5 |
2 | 3,7,8,9 |
3 | 4,5,10 |
Curent query:
$value = '3';
$query = "SELECT tag_ids FROM table WHERE FIND_IN_SET($value, tag_ids)";
$result = mysqli_query($query);
$count = mysqli_num_rows($result);
echo count;
Result will be: YES/NO or 1/0, if the Given value is match any value with tag_ids.
I found the result my self and here is code:
function statusvalues() {
$query = "SELECT tag_ids FROM tblname WHERE tag_ids !=''";
$result = mysqli_query($query, DBCONN);
$idarray = array();
while($row = mysqli_fetch_array($result)) {
array_push($idarray, $row['tag_ids']);
}
return $idarray;
}
function status($ID) { //Passing tag id
$set_of_numbers = statusvalues();
$reset_numbers = implode(", ", $set_of_numbers);
$values = explode(", ", $reset_numbers);
if (in_array($ID, $values)){
return "disabled";
}
}

Assign variables from array

I created a settings table in my database and I would like to assign value to a variable based on the setting and I'm not sure how to go about doing it.
table: settings
id | setting | value
1 | setting_one | value_one
2 | setting_two | value_two
3 | setting_three | value_three
Query
if ($result = $db->query("SELECT * FROM settings")) {
while($row = mysqli_fetch_assoc($result)) {
$SettingOne = $row['setting_one'];
$SettingTwo = $row['setting_two'];
$SettingThree = $row['setting_three'];
}
}
The select will return you 3 rows, assuming your table has only 3 rows in it
that is why you process the result in a while lop.
Each $row will contain an Assoc array in the form of the columns that you selected in your query.
In this case as you use SELECT * the $row array will contain 3 occurances
id, setting, value
So your loop should look like
if ($result = $db->query("SELECT * FROM settings")) {
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$setting = $row['setting'];
$value = $row['value'];
echo "The id = $id, the setting = $setting, the value is $value <br>";
}
}
This will produce you 3 lines of output, assuming you only have 3 rows in your table
I got it figured out and just echo the row['setting'] as $setting for each :)
if ($result = $db->query("SELECT * FROM settings")) {
while($row = mysqli_fetch_assoc($result)) {
$key = $row['setting'];
$$key = $row['value'];
}
$result->free();
$result->close();
}

UPDATE query through foreach loop in mysql/php

I do have an array something like this:
[cuisines] => Array
(
[0] => 17
[1] => 20
[2] => 23
[3] => 26
)
Now I need to update mysql table with these values. All values belong to one user.
So I tried it like this:
if (isset($_POST['cuisines'])) {
$cuisines = $_POST['cuisines'];
} else {
$error_alert[] = "Please select at least one cuisine";
}
if (empty($error_alert)) { // If everything's OK...
// Make the update query:
$sql = 'UPDATE restaurant_cuisines
SET restaurant_id = ?
, cuisine_id = ?
WHERE restaurant_id = ?';
$stmt = $mysqli->prepare($sql);
// Bind the variables:
$stmt->bind_param('iii', $restaurant_id, $cuisine_id, $restaurant_id);
foreach ($cuisines as $value) {
$cuisine_id = $value;
// Execute the query:
$stmt->execute();
}
// Print a message based upon the result:
if ($stmt->affected_rows >= 1) {
echo 'updated';
}
// Close the statement:
$stmt->close();
unset($stmt);
}
But this query not updating mysql correctly. This is what I get running this script.
mysql> select * from restaurant_cuisines where restaurant_id = 4;
+---------------+------------+
| restaurant_id | cuisine_id |
+---------------+------------+
| 4 | 26 |
| 4 | 26 |
| 4 | 26 |
+---------------+------------+
3 rows in set (0.00 sec)
What would be the problem of this script?
Hope somebody may help me out.
Thank you.
You need to bind your parameters in the loop:
// Delete old entries:
$sqlDelete = 'DELETE FROM restaurant_cuisines WHERE restaurant_id = ?';
$stmtDelete = $mysqli->prepare($sqlDelete);
$stmtDelete->bind_param($restaurant_id);
$stmtDelete->execute();
$stmtDelete->close();
unset($stmtDelete);
// now prepare to insert new values
$sqlInsert = 'INSERT INTO restaurant_cuisines (restaurant_id,cuisine_id)
VALUES (?,?)';
$stmtInsert = $mysqli->prepare($sqlInsert);
foreach ($cuisines as $value) {
// Bind the variables:
$stmtInsert->bind_param($restaurant_id, $value);
// Execute the query:
$stmtInsert->execute();
// Print a message based upon the result:
if ($stmtInsert->affected_rows >= 1) {
echo 'updated';
}
}
// Close the statement:
$stmtInsert->close();
unset($stmtInsert);

Categories