Add multiple SQLresults to an array while in a foreach loop - php

I am having some trouble trying to get this done. The issue is:
I have an array that looks like
wants_arr_flat ( [0] => booze [1] => nudes [2]
=> rooms
I want my foreach loop to go through these values making a different SQL statement and then saving the result of that SQL statement on to another array. The code I am trying to work with now is this.
foreach ( $wants_arr_flat as $value ) {
$sql = "SELECT * FROM offers WHERE user_id != $_SESSION[user_id] AND offer='$value'";
$result=$conn->query($sql);
$want_match_arr = mysqli_fetch_row($result);
echo '<pre>'; print_r($want_match_arr); echo '</pre>'; //testing echo
Obviously this is just overwriting the last array each iteration so I only end up with one result in the array.

instead of
$want_match_arr = mysqli_fetch_row($result);
use
$want_match_arr[] = mysqli_fetch_row($result);

If you get multiple rows from SQL then this is better.
$want_match_arr = [];
foreach ( $wants_arr_flat as $value ) {
$sql = "SELECT * FROM offers WHERE user_id != $_SESSION[user_id] AND offer='$value'";
$result=$conn->query($sql);
while ($row = mysql_fetch_assoc($result)) {
$want_match_arr[] = $row;
}
}
echo '<pre>'; print_r($want_match_arr); echo '</pre>'; //testing echo

Related

array loop problem , it just show once time

I want to show the array, after array[0] has shown, show next data , loop to do that before have shown all data in database. e.g:
Array (
[0] => Array (
[ID] => 1 [name] => peter [time] = >1:00
)
[1] => Array (
[ID] =>2 [name]=> merry [time]=>3:00
)
...etc
I wish that:
-------------- |id|name |time|
-------------- |1 |peter|1:00|
-------------- |2 |merry|3:00|
-------------- |..|.....|.:..|
but the real is just only show array[0] . like that:
-------------- |id|name |time|
-------------- |1 |peter|1:00|
---------------
Can you tell me how to improve that and correct that?
$sql = "SELECT * FROM mytable";
$result = mysqli_query($conn, $sql);
$datas = array();
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result)){
$datas[] = $row;
}
}
$result = $conn->query($sql);
$x = 0;
$a = $datas[$x];
if($a = array())
{
echo "";
}
else
{
foreach($datas[$x] as $data){
echo $data."<td>"."<br>";
$x++;
}
}
There are quite a few issues in your code:
$result = $conn->query($sql) is redundant - you already ran exactly the same query a few lines earlier.
if($a = array()) makes no sense. I think you're probably trying to test whether $a is definitely an array? But what you're really doing is assigning a new empty array to it. It's irrelevant anyway because you never use $a for anything, and we know that $datas will always be an array, so there's no need to check if it's an array. If there are no rows, the loop just won't run.
Writing "<td>"."<br>" will generate invalid HTML. Either use tables and rows, or just use line breaks. You need to make up your mind. Tables is probably better for presenting tabular data...
Most importantly for your question, $datas[$x] only represents the first array of data in $datas. Your loop only loops over the items in that first array. You need to loop over all the indexes in $datas.
Here's a fixed version of your code:
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$datas = array();
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result)){
$datas[] = $row;
}
}
echo "<table>"; //start a table
echo "<tr><th>ID</th><th>Name</th><th>Time</th></tr>"; //print the table header
foreach($datas as $row) //loop over all the rows
{
echo "<tr>"; //start a new row
foreach ($row as $field) //loop over the fields in each row.
{
echo "<td>".$field."</td>"; //print a single field in a table cell
}
echo "</tr>"; //end the row
}
echo "</table>"; //end the table

foreach is not working while trying to get students

echo "<pre>"; print_r($jobbrnchesids); exit;
<pre>Array
(
[0] => Array
(
[id_branch] => 6
)
[1] => Array
(
[id_branch] => 1
)
)
From the above array, i am getting job id branches.. Now i am trying to Get the students who are with these branches.
i have tried like this way but it something is going wrong unable to debug can anyone help me out.
$studentBranch = '';
foreach ($jobbrnchesids as $k => $v){
$stuBranch = $conn->query("SELECT student_pid FROM tbl_students
WHERE graduation_branch = ".$v." ");
$studentsWithBranches[] = $stuBranch->fetch_assoc();
}
echo "<pre>"; print_r($studentsWithBranches); exit;
instead of $v it need to be $v['id_branch']
missing array index 'id_branch'
Try:
$stuBranch = $conn->query("SELECT student_pid FROM tbl_students
WHERE graduation_branch = ".$v['id_branch']." ");
Reduce your overhead by doing the following:
$branchIds = array_column($jobbrnchesids,"id_branch");
$result = $conn->query("SELECT student_pid FROM tbl_students
WHERE graduation_branch IN (".implode(",",$branchIds.")");
$studentsWithBranches = $result?$result->fetch_all(MYSQLI_ASSOC):[];
array_column Returns the values from a single column in the input array
$studentBranch = '';
foreach ($jobbrnchesids as $k => $v) {
$stuBranch = $conn->query("SELECT student_pid FROM tbl_students WHERE graduation_branch = '" . ['id_branch'] . "'");
$studentsWithBranches[] = $stuBranch->fetch_assoc();
}
echo "<pre>";
print_r($studentsWithBranches);
exit;

How to return an entire column as an array using PHP

I am trying to fetch a column from a database and display the entire contents as an array. I have so far been able to fetch only one of the entries from the table. I understand that I am fetching only $row[0] which is why i am getting only 1 element. I have tried to fetch all elements but I have not succeeded yet. can someone please let me know how to do it correctly? I have attached my code below.
<?php
$con=mysqli_connect("localhost","root","raspberry","users");
if (mysqli_connect_errno())
{
echo "failled to connect:".mysqli_connect_error();
}
$sql = "SELECT `current` FROM `monitor` ORDER BY `Sno.`";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_NUM);
printf("%s\n",$row[0]);
mysqli_close($con)
?>
PDO has a dedicated feature for your problem PDOStatement::fetchColumn.
So, from your question what I understand is- you want to fetch a database column and store this in a array which will make you to display the results.
<?php
$con=mysqli_connect("localhost","root","raspberry","users");
if (mysqli_connect_errno())
{
echo "failled to connect:".mysqli_connect_error();
}
$sql = "SELECT current FROM monitor ORDER BY Sno";
$result = mysqli_query($con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)) {
$arr2 = array();
foreach ($row as $val) $arr2[] = $val;
$arr[] = $arr2;
}
$first_col = array_column($arr, 0);
print_r($first_col);
mysqli_close($con)
?>
i.e. if you have five entry to the database whose first column contains
the values like 'current1', 'current2', 'current3', 'current3' and 'current4' the result of this code will be
Array
(
[0] => current1
[1] => current2
[2] => current3
[3] => current4
[4] => current5
)

How to change php array output

I have the following function:
public function albums($artist) {
$artist = $this->db->sanitize($artist);
$query = "
SELECT `album`, `cover`
FROM `albums`
join `artists`
on `albums`.`artistsID` = `artists`.`id`
WHERE `artists`.`artist` = ?
";
$stmt = $this->db->mysqli->prepare($query);
$stmt->bind_param('s', $artist);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
As you can see this will return an array with the album name and the cove file path.
The array output looks like this:
Array
(
[0] => Array
(
[album] => Album name
[cover] => file path
)
[1] => Array
(
[album] => Album name
[cover] => file path
)
)
As you can see it returns an array with 0 and 1 with an array of album and cover.
What I would like it to be is an array which is easier to use with a while loop.
So I can do something like:
while($row = $data) {
echo $row['album'].' <img src="'.$row['cover'].'">';
}
instead of 2 foreach loops like I have to do now. So my question is how can I get an array which is easier to use like you would normaly get when you do something like:
<?php
$query = mysqli_query($connect, "SELECT `username` FROM `users` WHERE `id` = 1");
while($row = mysqli_fetch_assoc($query)) {
echo $row['username'];
} //Just as an example to make the question a bit more understandable
?>
I hope someone could help me out on this one. If you need more information please let me know.
What I would like it to be is an array which is easier to use with a while loop
You should rather use a foreach loop for this … then the whole “problem” solves itself without any further meddling with the array structure.
You're using fetch_assoc() so...
while($row = $result->fetch_assoc()) {
echo $row['album'] . ' <img src="' . $row['cover'] . '">';
}

php getting values out of an array with same 'id' number

I'm having trouble getting the value out of an array
Array
(
[0] => id
[column_name] => id
)
Array
(
[0] => businessType
[column_name] => businessType
)
Array
(
[0] => name
[column_name] => name
)
Array
(
[0] => city
[column_name] => city
)
...
I'm getting those values from
mysql_query("
SELECT column_name
FROM information_schema.columns
WHERE table_name='businessUpgrade'
")
And in my while loop
while($row = mysql_fetch_array($result)){
while($column = mysql_fetch_array($colName)){
if($row[$i] == 1){
//here comes the missing part
}
$i++;
}
}
I tried diffrent things, but according to print_r, the values I need to get have the same number of id (0). Is there any way, I can get the values out of this array.
I found that I should do it with foreach, but somehow everything I try it fails.
There is no need to use 2 while loops.
The $row array is an associative array, so you can use...
$columns = array();
// {query}
while($row = mysql_fetch_array($result)) {
$columns[] = $row['column_name'];
}
var_dump($columns);
Your $columns array now contains an index of all the columns. It's a zero-index, so these can be pulled individually using:
echo $columns[0]; // The first column from the query "id"
echo $columns[2]; // The third column from the query "name"
You can also loop this array as needed.
foreach ($columns as $id => $column) {
if ($id == 0) {
// Do something with the first column:
echo $column;
} elseif ($id == 2) {
// Do something with the third column:
echo $column;
}
}
try this
$res = mysql_query("
SELECT column_name
FROM information_schema.columns
WHERE table_name='businessUpgrade'
");
while($r = mysql_fetch_row($res)){
$arr[]=$r;
}
NOTE . do not use mysql. Try mysqli or PDO instead.
And with this:
while($row = mysql_fetch_array($result)){
while($column = mysql_fetch_assoc($colName)){
if(($column['0'] == $row[$i]) && ($row[$i] == 1)){
//something like this???
}
}
$i++;
}
Your question is a bit messy XD.....i hope this helps anyway.

Categories