PHP Create an array from fetch array - php

I have a Mysql query that gives the following result as using
while($row = mysql_fetch_array($res))
x | 12432
y | 232432
z | 323423
I want to take each column and put it in a new array in order to export them in a table that would look like
x | y | z
12432 | 232432 | 323423
If I fetch the same query more than once, the second row does not show up.
Can you please help?

Edit: Switch to mysqli (or PDO) as soon as you can! Plenty of reasons can be found in searchengines, so im gonna leave that to you.
You can use a nested loop to do this:
$array = array();
while($row = mysql_fetch_array($res)){
foreach($res as $key=>$value){
$array[$key][] = $value;
}
}
The first round of the while will give the $array the key-names and their first value, the next litterations through the loop will only add values

That is the code that worked for me.
while($row = mysql_fetch_array($res)){
$clients[] = $row[0];
$stats[] = $row[1];
}
foreach ($clients as $client)
{
echo "<td>$client</td>";
}
echo "</tr><tr>";
foreach ($stats as $stat)
{
echo "<td>$stat</td>";
}

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

if a value is on mysqli database do not create a button on php

I have a database table like
-----------------
| id | time |
|----|----------|
| 1 | 9am-10am |
| 2 | 11am-12pm|
and a PHP array
$times= array("8am-9am","9am-10am","10am-11am","11am-12pm","12pm-1pm","1pm-2pm","2pm-3pm","3pm-4pm","4pm-5pm","5pm-6pm","6pm-7pm","7pm-8pm","8pm-9pm","9pm-10pm");
My problem is, if the time is already in the database, the code shouldn't create a button with that value so I have the following foreach loop
$sql = "SELECT * FROM `time_table`";
$result = mysqli_query($conn,$sql);
foreach($times as $value){
while($row=mysqli_fetch_assoc($result)){
if($value!=$row['time']){
echo "<button>$value</button>";
}
}
}
But instead of showing all other values not 9am-10am and 11am-12pm instead it just shows two 8am-9am button
Try changing your code to this:
$sql = "SELECT * FROM `time_table`";
$result = mysqli_query($conn,$sql);
foreach($times as $value){
mysqli_data_seek($result,0); //reset the pointer to search from the first row every time
while($row=mysqli_fetch_assoc($result)){
if($value==$row['time']){
continue 2; //exits while loop and then skips foreach to the next $value
}
}
echo "<button>$value</button>";
}
Or the other solution (based on the other answer, so credits to JoSSte, but slightly modified, so it wouldn't have to iterate through the array):
$savedValues = array();
$sql = "SELECT * FROM `time_table`";
$result = mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result)){
$savedValues[$row['time']] = 1;
}
foreach($times as $value){
if(!isset($savedValues[$value])){
echo "<button>$value</button>";
}
}
It should work if you use in_array() and separate the loops, that way it will get more readable.
$sql = "SELECT * FROM `time_table`";
$result = mysqli_query($conn,$sql);
$resultTimes = array();
// Assign the DB values to an array
while($row=mysqli_fetch_assoc($result)){
$resultTimes[] = $row['time'];
}
// Check if values from $times are in the array, if not echo button
foreach ($times as $value) {
if (!in_array($value, $resultTimes)) {
echo "<button>$value</button>";
}
}
You are only running through the mysqli_resultset once, on the first instance of your foreach.
You need to rethink your logic. Fetch the mysql result outside your foreach, put the results in an array, and then use that array in a foreach instead of your while loop.
//first, fetch the rows from DB
$savedValues = array();
$sql = "SELECT * FROM `time_table`";
$result = mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result)){
$savedValues[] = $row['time'];
}
//then compare
foreach($times as $value){
foreach($savedValues as $svd){
if($svd != $value){
echo "<button>$value</button>";
}
}
}
NOTE: this is not optimal. as another comment states, you should consider in_array() or something similar to avoid loops in loops

MySQL Row in one output

Im pretty new to MySQl and PHP. I need some help with a small issue.
My statement is as follows:
while($row = $stmt->fetch()) {
$return_arr[] = $row['name'];
$return_arr[] = $row['value'];
}
It outputs as follows:
Mr James Jones
23
How can I bring it together into one line? Like this:
Mr James Jones 23
Thank you
Use implode to join the array elements:
echo implode(' ', $return_arr);
Do like this
while($row = $stmt->fetch()) {
$return_arr[] = $row['name']." ".$row['value'];
}
//print_r($return_arr); // The results gets printed as you expected or you could make use of a foreach construct as shown below.
//Printing using a foreach construct
foreach($return_arr as $k=>$v)
{
echo $v;echo "<br>";
}
Just use like this,
while($row = $stmt->fetch()) {
$return_arr[] = $row['name']. ' '.$row['value'];
}
it will work.
And if you want any other help let me know.
An alternate way is handling it inside your mysql query:
SELECT CONCAT(name, ' ', value) as name_and_value FROM ....
Than you can use
$row['name_and_value']
in your php code.

rewind one step back in mysql_fetch_array()

this is the values in the $result
id name
1 a
2 b
2 c
2 d
3 e
..
I'm creating a loop function using mysql_fetch_array()
while($row = mysql_fetch_array($result)) {
$temp_id = $row['id'];
while($temp_id == $row['id']) {
if($temp_id == $row['id']) {
mysql_fetch_array($result);
}
$temp_id = $row['id'];
echo $row['name'].",";
}
echo "<br/>";
}
this works but the problem is, the mysql_fetch_array jumps on one of the values during the transition of the id's..
I want the values of this to be like these
a
b,c,d
e
my question is, is there a simple rewind function that will step only once in the rows?
I have searched about the mysql_data_seek() but I think this would require additional control variables like $i to locate the address..
thanks.. any suggestions and function samples will be very great!
Use one loop with mysql_fetch_array first to create an array of the rows. Then, iterate over the rows themselves.
Based on the update to your question it seems like you would want to use GROUP_CONCAT in the query, but you can still do it in PHP:
$rows = array();
while($row = mysql_fetch_assoc($result)) {
if (!isset($rows[$row['id']]) {
$rows[$row['id'] = array();
}
$rows[$row['id']][] = $row['name'];
}
foreach ($rows as $row) {
echo implode(',', $row) . "<br>";
}
Try this code
while($row = mysql_fetch_array($result)) {
$temp[$row['id']][] = $row['name'];
}
foreach($temp as $row) {
echo implode(',', $row) . '<br/>';
}

How to sum result of query

I have one query where the output processing looks like this:
while($row = mysql_fetch_array($result)){
echo $row['username'] . " " . $row['earning'];
}
And outputs result is like this:
JOHN 200
JOHN 350
NEO 100
NEO 220
What I want to achieve is that every name appears once, and "earning" is sum of all earnings of that name, like this:
JOHN 550
NEO 320
I have to mention that I CANNOT change the query; that is biggest problem.
Is there any hope? Some suggestions? :)
You can sum the values in the loop to another array and then output it.
Try:
$earnings = array();
while($row = mysql_fetch_array($result)) {
if (!isset($earnings[$row['username']])) $earnings[$row['username']] = 0;
$earnings[$row['username']] += $row['earning'];
}
foreach($earnings as $user => $earnings) {
echo "$user $earnings<br />\n";
}
try:
$user = array();
while($row = mysql_fetch_array($result)){
$user[$row['username']] += $row['earning'];
}
to do echo :
foreach($user as $key => $value) {
echo $key."=". $earnings."<br>";
}
To get a quick solution to this answer you may want to simply append these results to an associated array and then simply loop over it to get the final count.
So, something like this:
$names= array();
while($row = mysql_fetch_array($result)){
$names[$row["username"]] += $row["earning"];
}
foreach($names as $k => $v) {
echo $k." ".$v."\n";
}
Instead of just selecting the data, select the field and SUM(otherfield) with otherfield being the field with the number to be summed. Then add GROUP BY with the first field.
try this in mysql side you don't need to calculate in php side so don't change your PHP side code jst change query like this
SELECT
username,
SUM(earning)
FROM yourtable
GROUP BY (username)
hope its will work for you

Categories