Separate multiple query row results? - php

The mysql query result can have 1 or 2 rows with results. How would I separate them?
$bio = mysql_query("SELECT *, FROM soc_meminfo
WHERE m_id = '".mysql_real_escape_string($en['id'])."'");
#
if (mysql_num_rows($bio) == 0) call404();
$line = mysql_fetch_assoc($bio);
foreach ($line as $key => $value) {
$en['b'.$key] = str_replace("\n",'<br/>',stripslashes($value));
}

Try this:
while ($row = mysql_fetch_assoc($bio)) { ... }
Also your sql should be SELECT * FROM soc_meminfo

try this
while ($row = mysql_fetch_assoc($bio)){
foreach ($row as $value){
echo $value;
}
echo '<br>';
}

I'm not sure I understand it, but try this.
$bio = mysql_query("SELECT *, FROM soc_meminfo
WHERE m_id = '".mysql_real_escape_string($en['id'])."'");
#
if (mysql_num_rows($bio) == 0) call404();
$line = mysql_fetch_assoc($bio);
foreach ($line as $key => $value) {
$en['b'.$key][] = str_replace("\n",'<br/>',stripslashes($value));
}

Related

MySQLi why am I only getting 1 result?

There are three "BC" in the result_category but I am only getting 1 result. This is for a personality quiz. Please Help. I also tried $query = "SELECT result FROM quiz_map where result_category = 'BC'"; but still, only 1 result is showing.
$result = mysqli_query($link, $query);
$cat_a = $cat_b = $cat_c = $cat_d = $cat_e = 0;
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$cat = $row['category'];
if ($cat == "A") {
$cat_a += 1;
} elseif ($cat == "B") {
$cat_b += 1;
} elseif ($cat == "C") {
$cat_c += 1;
} elseif ($cat == "D") {
$cat_d += 1;
} elseif ($cat == "E") {
$cat_e += 1;
}
}
$array = array('A' => $cat_a, 'B' => $cat_b, 'C' => $cat_c, 'D' => $cat_d, 'E' => $cat_e);
$str = '';
foreach ($array as $i => $value) {
if ($value >= 6) {
$str = $i;
break;
} elseif ($value >= 2) {
$str .= $i;
}
}
$var = sort($array);
$query = "SELECT result FROM quiz_map where result_category = '$str' LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
echo $row[0];
?>
There's many things wrong with your code!
As pointed by #IsThisJavascript and #Cashbee:
You are executing a query with a LIMIT 1 statement, it will only return one record.
As pointed by myself:
Doing echo $row[0] will have the same result, if you are only echoing the first value of the array you can't expect to have multiples can you?
As pointed by #IsThisJavascript:
You need to loop the results array, like so:
while($row = mysqli_fetch_array($result)){
echo $row['result_category'];
}
Consider switching the query from a '=' to a '%like%' statement, to maximize results if you want to get the values that partionaly cointain the string.

PHP counting MYSQL rows that contain the same value in many columns

Here is the content of my table:
How to count all names in different table cells to get a result like this?
Bob-7
Alex-3
Ivan-5
Nina-5
.........
With this code:
<?php
$q= mysqli_query($db, 'SELECT * FROM names');
while ($all = mysqli_fetch_array($q)) {
$k1= $all['Name1'];
$k2= $all['Name2'];
$k3= $all['Name3'];
$k4= $all['Name4'];
$k5= $all['Name5'];
$k6= $all['Name6'];
$arr[]= $k1;
$total_values = array_count_values($arr);
}
foreach ($total_values as $key => $value) {
echo $key .'-'. $value .'<br>';
}
My output result is:
Bob-3
Alex-1
Ivan-1
Nina-2
When I change my code to:
<?php
$q= mysqli_query($db, 'SELECT * FROM names');
while ($all = mysqli_fetch_array($q)) {
$k1= $all['Name1'];
$k2= $all['Name2'];
$k3= $all['Name3'];
$k4= $all['Name4'];
$k5= $all['Name5'];
$k6= $all['Name6'];
$arr=array($k1, $k2);
$total_values = array_count_values($arr);
foreach ($total_values as $key => $value) {
echo $key .'-'. $value .'<br>';
}
}
My output result is:
Bob-1
Alex-1
Ivan-1
Nina-1
Nina-1
Bob-1
Bob-1
Ivan-1
Nina-1
Nina-1
.......
What is wrong and what I have to do to add $k2, $k3....$k6 in the array $arr?
This will count the number of occurences for a single name:
$q= mysqli_query($db, 'SELECT * FROM names');
$arr = array();
// 1) loop through rows
while ($all = mysqli_fetch_array($q, MYSQLI_NUM)) {
// 2) loop through cells in a row
foreach($all as $val) {
// 3) 'roll out' the values into a one-dimensional array
if(empty($val)) { continue; } // if you don't want to count empty cells
$arr[] = $val;
}
}
// 4) count the number of occurences
$names_qty = array_count_values($arr);
// optional loop that shows the results
foreach($names_qty as $name=>$qty) {
echo $name.'-'.$qty.'<br />';
}
The benefit of this solution is that you call the counting function only once and not in every iteration.
You have to accumulate data in a loop and print it after all data is processed.
$total = array();
$result = mysqli_query($db, 'SELECT * FROM names', MYSQLI_USE_RESULT);
while (mysqli_fetch_assoc($result) as $row) {
foreach ($row as $col => $value)
total[$col]++;
}
}
print_r($total);
This code is tested and should do the trick.
<?php
$arr = array();
$q = mysqli_query($db, 'SELECT * FROM names');
while ($all = mysqli_fetch_assoc($q)) {
foreach($all as $val) {
if(empty($val)) {
continue;
}
// saves all names with the name as key
$arr[$val][] = $val;
}
}
// Output
foreach($arr as $k => $v) {
// count how many times the name was pushed into the array
echo $k.' - '. count($v);
}

Database results into 3 equal columns

I've got a very minor problem but it's one I'd like to work out, so I'm looking for suggestions.
I'm using the following PHP code to echo the data from an array.
$array = array();
$rsa = $wpdb->get_results("SELECT * from wp_letter ORDER BY l_name ASC");
foreach($rsa as $rrr)
{
array_push($array,$rrr->l_name);
}
$temp = 0;
foreach($array as $as)
{
$temp = 0;
$query = $wpdb->get_results("SELECT * FROM wp_term_taxonomy AS tx, wp_terms AS trm WHERE taxonomy = 'category' AND trm.term_id = tx.term_id AND name like '".$as."_%' ORDER BY name ASC");
foreach($query as $row1)
{
if($temp == 0)
{
echo '<h4>'. $as.'</h4>';
$temp = 1;
}
?>
<a class="anchor" href="<?php echo esc_url(get_category_link($row1->term_id)); ?>"><?php echo $row1->name;?></a><br/>
<?php }
} ?>
Just add the LIMIT 3 into your Query, e.g.
SELECT * from wp_letter LIMIT 3 ORDER BY l_name ASC;
You could either use some crap like (for example):
$query = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$results = ['1col' => [], '2col' => [], '3col' => []];
foreach($query as $key => $result) {
if (($key+1) % 2 === 0 && !(($key + 1) % 3 === 0)) {
$results['2col'][] = $result;
} elseif (($key+1) % 3 === 0) {
$results['3col'][] = $result;
} else {
$results['1col'][] = $result;
}
}
OR just smth like this:
$results = array_chunk($query, ceil(count($query)/3));
Links:
array_chunk
ceil

how to store associative array php MySQL

I want to store result of a query as associative array. Below is my code that generates the query result below.
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
foreach ($data_array as $key => $value)
{
echo $key.'=>'.$value.'<br />';
}
?>
This gives me output as
19=>Array
20=>Array
21=>Array
27=>Array
29=>Array
But I should get
19 -> [4,5],
20 -> [5],
21=>[4,6],
// and so on
$value is an array, you can't use echo on arrays
Don't loop just do a var_dump()
$data_array = array();
while($rs = mysql_fetch_assoc($result)){
$data_array[$rs['id']][]=$rs['Sprinkler_ID'];
}
var_dump($data_array);//or print_r($data_array);
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
$out = '';
$count = count($data_array);
$iter = 0;
foreach ($data_array as $key => $value)
{
$out.= $key.'=>[';
foreach ($value as $val) {
$out.=$val.',';
}
$out = rtrim($out, ",");
$out.= ']';
if ($iter < ($count-1)) {
$out.=',<br />';
}
$iter++;
}
echo $out;
You need an inner foreach loop to handle printing the array in $value as this is a multi dimensional array. The preceding is an example of how it could look to produce the exact output you requested. If you are looking for a dump of the values, then please use the var_dump solution provided by #meda.
There are two issues in your code. The first is that $value is an array, the second is that this array only contains one item.
Try this:
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key][] = $value;
}
foreach ($data_array as $key => $values)
{
echo $key.'=> [';
foreach($values as $value)
echo $value . ',';
echo ']<br />';
}

Exclude last comma in php array

I have a simple database connection:
$rowdata = mysql_query("SELECT * FROM table_names");
while($row = mysql_fetch_array($rowdata)) {
echo "".$row['name'].",";
}
I would like it to print out:
Adam, Sophia, Tom, Brian
instead of:
Adam, Sophia, Tom, Brian,
How do I exclude the last comma in the best way?
$rowdata = mysql_query("SELECT name FROM table_names");
$names = array();
while($row = mysql_fetch_array($rowdata)) {
$names[] = $row['name'];
}
echo implode(', ', $names);
Instead of echoing it straight out, put it into a variable (named $values perhaps) then do:
$values = rtrim($values,",");
Print the comma before each entry and omit the first one:
$first = TRUE;
while(($row = mysql_fetch_array($rowdata)) !== FALSE) {
if(!$first) echo ',';
echo htmlspecialchars($row['name']);
$first = FALSE;
}
Another way would be to use extract echoing the first line from the loop, that way the if statement does not have to be evaluated each iteration (premature optimization ftw!):
if(($row = mysql_fetch_array($rowdata)) !== FALSE)
echo htmlspecialchars($row['name']);
while(($row = mysql_fetch_array($rowdata)) !== FALSE) {
echo ',', htmlspecialchars($row['name']);
}
And finally you can do it in mysql:
select group_concat(name) from table_names
In full this would become:
$rowdata = mysql_query("SELECT group_concat(name) as names FROM table_names");
while($row = mysql_fetch_array($rowdata)) {
echo $row['names'];
}
$rowdata = mysql_query("SELECT * FROM table_names");
$names = array();
while($row = mysql_fetch_array($rowdata)) {
$names[] = $row['name'];
}
echo implode( $names, ',' );
By the way, if you're only using the 'name' column, it's better to do SELECT name FROM ..
Make it ..
$names = array();
while ( $row = mysql_fetch_array( $rowdata ) ) {
$names[] = $row['name'];
}
$names = implode(', ', $names);
echo $names;

Categories