mysqli - how to get exact ($i) raw field from query - php

Need to receive data of fields from $i raw of mysqli object.
$res = $mysqli->query("SELECT mood,count(mood) as number FROM em_mood GROUP by mood ORDER by mood ASC");
$obj = $res->fetch_object();
for ($i = 1; $i <= 10; $i++){
if ($i==$obj->mood[$i]) $mood_result .= "<div class='chart'>".$obj->mood[$i].$obj->number[$i]."</div>";
else $mood_result .= "<div class='chart'>empty</div>";
}
Explanation:
$obj->mood is equal from 1 to 10.
if $obj->mood is missing "2" for example, I need to exchange it with empty div.
In other words, what is the syntax of getting field [mood] value in lets say second raw? something like $obj[2][mood]?
Update:
Looks like it works like this:
for ($i = 1; $i <= 10; $i++){
$res = $mysqli->query("SELECT mood,count(mood) as number FROM em_mood WHERE date>=CURDATE()-INTERVAL 30 DAY and mood=".$i);
$obj = $res->fetch_object();
echo $obj->mood." - ".$obj->number."<br>";
}
Is there any way to make this more simple? To don`t make 10 mysqli queries?

$raw = [];
$sql = "SELECT mood,count(mood) as number FROM em_mood GROUP by mood";
$res = $mysqli->query($sql);
while ($obj = $res->fetch_object())
{
$raw[$obj->mood] = $obj->number;
}
now you will have your "raw" data all right
for ($i = 1; $i <= 10; $i++){
if (isset($raw[$i])) {
$mood_result .= "<div class='chart'>$i - $raw[$i]</div>";
} else {
$mood_result .= "<div class='chart'>empty</div>";
}
}

Related

mysql query id as variable not working

I want to update my MySQL table. When I type the ID as a number works, but when using a variable instead, it does not work.
What I am trying to do is order elements of an html table by column.
I have e.g. 4 Columns:
$colname = array("Column1", "Column2", "Column3", "Column4");
I get the IDs of the elements already sorted from the URL variable:
$strTaskIds = $_GET["taskIds"];
// for example: $strTaskIds = "3;1;32_4;5_6;36_34;7"
Now I split the string into a 2D-Array and update the MySQL table:
$arrTaskIds = explode("_", $strTaskIds);
for($i = 0; $i < count($arrTaskIds); $i++) {
$arrIdsPerCol = explode(";", $arrTaskIds[$i]);
for($j = 0; $j < count($arrIdsPerCol); $j++) {
$sql = "UPDATE tasks SET col='$colname[$i]', rank=$j WHERE id=$arrIdsPerCol[$j]";
}
if($conW->query($sql) === TRUE) {
$error = 0;
} else {
$error = 1;
}
}
When I write a number E.G 7 instead of the variable $arrIdsPerCol[$j] it works.
Writing (int)$arrIdsPerCol[$j] does not work either.
The reason i gave you no error message is that there was none. It just looked like the MySQL table is not updating.
After starring at my code for quite a long time a found the problem.
I placed the query() code in the outer loop. But i needed it in the inner loop.
Problem solved:
$arrTaskIds = explode("_", $strTaskIds);
$error = 0;
for($i = 0; $i < count($arrTaskIds); $i++) {
$arrIdsPerCol = explode(";", $arrTaskIds[$i]);
for($j = 0; $j < count($arrIdsPerCol); $j++) {
$sql = "UPDATE tasks SET col='$colname[$i]', rank=$j WHERE id=$arrIdsPerCol[$j]";
if($conW->query($sql) === TRUE) {
} else {
$error = 1;
}
}
}

While loop not working with x <=num

$x = 1;
$num = 15;
while($x <= $num) {
$res = '[TR][TD="align: left"]'.$x.'[/TD][TD="align: left"][/TD][/TR]';
$x++;
}
echo $res;
That's my code but it only shows the following when I try it:
[TR][TD="align: left"]15[/TD][TD="align: left"][/TD][/TR]
It should show that but instead of only 15 it should be 1-15 inclusive.
Any ideas?
You keep setting $res to a new value rather than appending to it. Using $res .= 'something'; is like saying $res = $res . 'something';. Doing this will allow you to keep the previous value of $res and appending more to the end of it.
$x = 1;
$num = 15;
$res = '';
while($x <= $num) {
$res .= '[TR][TD="align: left"]'.$x.'[/TD][TD="align: left"][/TD][/TR]';
$x++;
}
echo $res;
$x = 1;
$num = 15;
while($x <= $num) {
$res = '[TR][TD="align: left"]'.$x.'[/TD][TD="align: left"][/TD][/TR]';
$x++;
echo $res;
}
Put echo $res; inside the loop, otherwise it will echo just the $res from the last loop cycle instead of all 15 times.

Array outside while doesn't function

Sorry for the beginner question.
I'm searching about an hour, but I can't understand why my $row outside from the second while doesn't function... The name variable run just the $row var doesn't function...
$i = 0;
while($i < 8)
{
$str = "SELECT * FROM `$name[$i]`";
$result = mysql_query($str, $connessione);
$l = mysql_num_rows($result);
while($l > 1)
{
$strs = "SELECT * FROM `$name[$i]` WHERE `Livello` = '$l'";
$results = mysql_query($strs, $connessione);
$row[$i][$l] = mysql_fetch_array($results);
if I put here the echo I can view the mysql variable
echo $row[$i][$l]['var'];
$l--;
}
if I put here echo $row[$i][$l]['var']; he send me the error " Undefined offset"
$i++;
}
Hope you can help me...
In the place where you put:
echo $row[$i][$l]['var'];
$l value is 0 and you set $row values for $l from 1 to mysql_num_rows($result)
if you put there:
echo $row[$i][1]['var'];
it should work fine assuming mysql_num_rows($result) was more than 1 element.
Probably your code should look like this:
$i = 0;
while($i < 8)
{
$str = "SELECT * FROM `$name[$i]`";
$result = mysql_query($str, $connessione);
$l = mysql_num_rows($result);
while($l > 0) // changed 1 to 0
{
$strs = "SELECT * FROM `$name[$i]` WHERE `Livello` = '$l'";
$results = mysql_query($strs, $connessione);
$row[$i][$l] = mysql_fetch_array($results);
if i put here the echo i can view the mysql variable
echo $row[$i][$l]['var'];
$l--;
}
// added extra loop to display array values
$whileIndex = 0;
while (true) {
if (!isset($row[$i][$whileIndex]['var']) {
break;
}
echo $row[$i][$whileIndex]['var']; // should work
++$whileIndex;
}
$i++;
}
When you try to use echo, $i = 8 and $l = 1. These keys doesn´t exists in your array.

randomly choose one data from blocks of query

I have 100000 records in a table. I need to make a query that reads 10 records and after that 10 more records continuously until the end of the table. For each of the 10 rows groups, I need to pick one random row. Is it possible to accomplish that using a MySQL query? I need some idea to do this. Can anybody help me?
I have tried to do a php loop but it doesn't work.
<?php
include_once ("connection.php");
$data = mysql_query("SELECT * FROM trying");
$result = array();
while ($data2 = mysql_fetch_array($data))
{
array_push($result, array('no'=> $data2['no'],
'source'=> $data2['source'],
'destination'=> $data2['destination']));
}
$e=0;
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
?>
Insted of this:
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
you can use this:
$rand = array();
$step = 10;
for ($min = 0; $min <= 49; $min = $min + $step)
{
$max = $min + $step;
$rand[] = $result[rand($min,$max)];
}
echo json_encode($rand);
Since you're echoing a json encoded array, I'm assuming you're calling this php file through an AJAX request, and you want subsequent requests for each 10 rows.
If this is the case, a solution to your problem could be this:
Define limit and offset as vars in your javascript
Pass limit and offset with the AJAX request
If the result of the AJAX request isn't empty, increment offset by limit (offset = offset + limit) to use in the next request
Receive limit and offset in the PHP file (use $_GET or $_POST, depends on the type of request)
Include limit and offset in the MySQL query ("SELECT * FROM trying LIMIT $offset, $limit")
Calculate a random number from 0 to 9 (rand(0, 9))
Fetch the nth (rand) row from the MySQL result (see solution below)
Your PHP file should look like this:
include_once ("connection.php");
$limit = mysql_real_escape_string($_GET['limit']); // If post use $_POST
$offset = mysql_real_escape_string($_GET['offset']); // If post use $_POST
$data = mysql_query("SELECT * FROM trying LIMIT $offset, $limit");
$rand = rand(0, 9);
$count = 0;
while($row= mysql_fetch_array($data)) {
if($rand == $count++) {
echo json_encode($row);
break;
}
}
Put the SQL statement in a loop and use the counter as a variable in the Limit:
$count = mysql_query("SELECT * FROM trying");
$total = round(mysql_num_rows($count) / 10);
for ($i=0;$i<$total;$i++) {
$data = mysql_query("SELECT * FROM trying LIMIT ".($i * 10).", 10");
$result = array();
while ($data2 = mysql_fetch_array($data))
{
array_push($result, array('no'=> $data2['no'],
'source'=> $data2['source'],
'destination'=> $data2['destination']));
}
}
$e=0;
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
?>
Try with the following:
<?php
include_once ("connection.php");
$query = "SELECT * FROM trying";
$count = 0;
while(true)
{
$data = mysql_query($query." LIMIT ".$count.",10");
$random = rand(1,10);
for($i=1;$i<=$random;$i++)
{
$row = mysql_fetch_array($data);
if($row === false)
{
break 2;
}
}
echo json_encode($row);
$count++;
}
?>
Try this :
<?php
set_time_limit(0);
include_once ("connection.php");
$per = 10;
$start = 0;
$total = 0;
$total_query = mysql_query("SELECT COUNT(*) AS total FROM trying");
if(mysql_num_rows($total_query) == 1) {
$row = mysql_fetch_assoc($total_query);
$total = $row['total'];
$offset = ($start * $per);
$results = array();
while($offset <= $total) {
$tmp = array();
$data_query = mysql_query("SELECT * FROM trying LIMIT ".$offset.",".$per);
while ($row = mysql_fetch_array($data_query)) {
array_push($tmp, array(
'no'=> $row['no'],
'source'=> $row['source'],
'destination'=> $row['destination'])
);
}
array_push($results,$tmp[rand(0,9)]);
unset($tmp);
$start++;
$offset = ($start * $per);
}
echo json_encode($results);
} else {
die("No records found.");
}
?>

Group and sum duplicate elements in a for loop

I have a for loop like so:
for((int) $i = 0; $i < $number_of_updates; $i++)
{
//query here
$result = mysql_query($query);
list($name) = mysql_fetch_row($result);
$points = 1;
//some functions to execute here... and then
//store results in session to show on other page
$output = $points.' times '.$name;
$_SESSION['item'][] = $output;
}
And then I show my results on view page like so:
foreach (array_unique($_SESSION['item']) as $output)
{
echo ('<p>'.$output.'</p>');
}
It echoes my results out of the loop like so:
1 times foo
1 times foo
1 times bar
1 times foo
etc...
Now the question. How do I sum those results up so they don't duplicate? Instead they are shown like so:
3 times foo
1 times bar
User array_count_values
for(/*(int) <- this is not neccessary (c++ background?) */ $i = 0; $i < $number_of_updates; $i++)
{
// your code
$_SESSION['item'][] = $name;
}
foreach(array_count_values($_SESSION['item']) as $name => $times)
echo ('<p>'.$times.' times '.$name.'</p>');
Of course counting the values directly is more memory and time efficient. This version is only neccessary if you somehow need to preserve the order of the elements.
Why didn't you store in your array directly the sum?
for((int) $i = 0; $i < $number_of_updates; $i++)
{
//query here
$result = mysql_query($query);
list($name) = mysql_fetch_row($result);
$points = 1;
//some functions to execute here... and then
//store results in session to show on other page
$_SESSION['item'][$name] +=$points;
}
Try this:
for((int) $i = 0; $i < $number_of_updates; $i++)
{
//query here
$result = mysql_query($query);
list($name) = mysql_fetch_row($result);
$points = 1;
//some functions to execute here... and then
//store results in session to show on other page
//$output = $points.' times '.$name;
//$_SESSION['item'][] = $output;
if( isset( $_SESSION['count'][$name] )){
$prev = $_SESSION['count'][$name];
}else{
$prev = 0;
}
$_SESSION['count'][$name] = $points + $prev ;
}
print_r( $_SESSION['count'] );

Categories