I have this code but when I run it it give me error ( Notice: Undefined offset: 1 in C:\wamp\www\test3.php on line $str[$row['term_no']] += ",".$row['code']; )
How can I solve this problem?
<?php
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, "uoh");
$q = " SELECT * FROM `degree_plan` LEFT JOIN courses ON
degree_plan.course_number=courses.course_number
where major='COE'";
$result = mysqli_query($con, $q);
if ($result) {
$str = [];
while ($row = mysqli_fetch_array($result)) {
{
$str[$row['term_no']] += "," . $row['code'];
}
foreach ($str as $key => $value) {
echo $value;
echo $key;
}
}
}
?>
In your code, you are puting all codes in one element which is never defined.
change this:
$str[$row['term_no']] += ",".$row['code'];
to this:
$str[$row['term_no']] = $row['code'];
The error happens because the array element doesn't exist, so, first check the element : if it exist, add, if it doesn't, create:
while($row = mysqli_fetch_array($result))
{
if ( isset( $str[$row['term_no']] ) ) // IF ELEMENT EXISTS...
$str[$row['term_no']] .= ",".$row['code']; // ADD TO ELEMENT.
else $str[$row['term_no']] = $row['code']; // CREATE ELEMENT.
}
Related
I get username (child) and referral (parent) records from database and put them into arrays by code below :
$sql = "SELECT username, referral FROM acc_status";
$q = $conn->prepare($sql);
$q->execute(array());
$data = array();
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$data[] = $row;
}
$map = array();
foreach ($data as $node) {
// init parent
if (!array_key_exists($node['referral'], $map)) {
$map[$node['referral']] = array();
}
// add to parent
$map[$node['referral']][$node['username']] = & $map[$node['username']];
}
echo '<pre>';
print_r($map["123"]); //get parents and child of username "123" only.
echo '</pre>';
And here is the output :
Now I want to covert the array into ul and li list, below is the code :
function printTree($tree) {
if(!is_null($tree) && count($tree) > 0) {
echo '<ul>';
foreach($tree as $node) {
echo '<li>'.$node['referral'];//error here
printTree($node['username']);//error here
echo '</li>';
}
echo '</ul>';
}
}
printTree($map["123"]);
I am getting 2 errors :
1) Notice: Undefined index: referral
2) Notice: Undefined index: username
How to fix the errors?
I'll be brief here, put simply the name of your referral and username is actually your index. So for $node['username'] it would be qqq I do not have my computer with me to show the working code however that's what it will be.
I would like to echo my results from a database and have them look like an array. They don't necessarily have to be an array but look like one. i.e. When i echo my result,
i would want my final result to look like
[10,200,235,390,290,250,250]
When i try the code below:
$query_rg = mysqli_query($link, "SELECT column FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma = "$list,";
echo ltrim($listwithcoma,',');
}
echo ']'
The result is :
[10,200,235,390,290,250,250,]
You are doing it wrong. ltrim($listwithcoma,',') has no effect.
ltrim — Strip whitespace (or other characters) from the beginning of a string
You can try a simple way with implode.
$list = array();
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column'];
}
echo '[' . implode(',', $list) . ']';
Just use GROUP_CONCAT in query as
$query_rg = mysqli_query($link, "SELECT GROUP_CONCAT(`column` SEPARATOR ', ') as data
FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
print_r($row_rg['data']);
Try like this
$list = array(); //define a array.
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column']; //store column value in array.
}
$lists = "[".implode(",",$list)."]";
echo $lists; //will echo your results.
You should be using rtrim() function instead, that too outside the loop.
$listwithcoma = '';
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma .= "$list,";
// echo ltrim($listwithcoma,','); Remove this
}
echo rtrim($listwithcoma,','); // Add this
echo ']';
I am facing the follow error from the below code:
Error:
Warning: Invalid argument supplied for foreach()
Code:
//--------This is the code for jquery UI autocompleter-------------
include "inc/connect.php";
$skeyword = $_GET["term"];
$req = "SELECT p.prm_title ,a.am_name, c.cm_name ,l.lm_name ,b.bm_name,r.pm_name "
. "FROM product_master p,author_master a,category_master c,language_master l,binding_master b ,publisher_master r "
. "WHERE p.prm_title LIKE '%$skeyword%' OR a.am_name LIKE '%$skeyword%'
OR c.cm_name LIKE '%$skeyword%' OR l.lm_name LIKE '%$skeyword%' OR b.bm_name LIKE '%$skeyword%' OR r.pm_name LIKE '%$skeyword%'
GROUP BY p.prm_id LIMIT 10";
$res = mysql_query($req);
$ret = array();
foreach (mysql_fetch_array($res) as $row) {
foreach ($row as $val) //--Error: from this line, Why?
{
if (false !== stripos($val, $skeyword)) {
$ret[] = $val;
break;
}
}
}
$testme = json_encode($ret);
echo $testme;
The above code is written for jquery auto-completer to search in many column field, but it will return only the matched column.
Please help me to solve this issue..
why:
If a variable:
is not array
does not implements the interface Iterator
and it is used to iterator by foreach, this error will raise.
How to fix
mysql_fetch_array returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows, so use a while loop to fetch result:
while ($row = mysql_fetch_array($res))
{
// if $row is false, the code will not hit here.
foreach ($row as $val)
{
if (FALSE !== stripos($val, $skeyword))
{
$ret[] = $val;
break;
}
}
}
update:
while ($row = mysql_fetch_array($res))
{
// if $row is false, the code will not hit here.
foreach ($row as $val)
{
if (FALSE !== stripos($val, $skeyword) && !in_array($val, $ret))
{
$ret[] = $val;
break; // what this break for?
}
}
}
Please try this.
Use while instead of foreach
//--------This is the code for jquery UI autocompleter-------------
include "inc/connect.php";
$skeyword = $_GET["term"];
$req = "SELECT p.prm_title ,a.am_name, c.cm_name ,l.lm_name ,b.bm_name,r.pm_name "
. "FROM product_master p,author_master a,category_master c,language_master l,binding_master b ,publisher_master r "
. "WHERE p.prm_title LIKE '%$skeyword%' OR a.am_name LIKE '%$skeyword%'
OR c.cm_name LIKE '%$skeyword%' OR l.lm_name LIKE '%$skeyword%' OR b.bm_name LIKE '%$skeyword%' OR r.pm_name LIKE '%$skeyword%'
GROUP BY p.prm_id LIMIT 10";
$res = mysql_query($req);
$ret = array();
while ($row = mysql_fetch_array($res))
{
foreach ($row as $val) //--Error: from this line, Why?
{
if (FALSE !== stripos($val, $skeyword))
{
$ret[] = $val;
break;
}
}
}
$testme = json_encode($ret);
echo $testme;
while ($row = mysql_fetch_array($res)) {
Again, but now as an answer:
Change your first foreach into a while loop. See the mysql_fetch_array manual
Please always verify that the parameter for the "foreach" is an array.
Your SQL request may return FALSE if there is no row matching your conditions, and foreach on FALSE does not work :)
So after your code
foreach (mysql_fetch_array($res) as $row)
You have to verify that $row is an array and not false before trying to iterate over it.
if (is_array($row))
Or you may be more explicit and use mysql_num_rows, which tells you if the query returns some rows or not :
if (mysql_num_rows($res) > 0)
{
$ret = array();
foreach ( mysql_fetch_array($res) as $row)
// ...
}
But the right solution, as exposed above by djot and Amol, is to use the
while ($row = mysql_fetch_array($res))
which ensure that if $row is FALSE, then you won't enter the block and you won't try to iterate on FALSE.
I want to make implode to display only 5 arrays after that it automatic creates a new row displaying 5 arrays again and it keep repeating itself. like is it possible to use <br /> or something else I had to use to do that?
$result = mysql_query("SELECT * FROM `im_album` WHERE username = '".$user_data['username']."' ");
$types = array();
$d_array = array();
while(($row = mysql_fetch_assoc($result))) {
$types[] = $row['name'];
$d_array[] = $row['description'];
}
echo "<h1>".implode($types )."</h1>"
Try this one:
$result = mysql_query("SELECT * FROM `im_album` WHERE username = '".$user_data['username']."' ");
$types = array();
$d_array = array();
$types_str="";
$types_str_array=array();
$temp=1;
while(($row = mysql_fetch_assoc($result))) {
$types_str .=$row['name'];
if($temp!=1 && $temp%5==0)
{
$types_str_array[]=$types_str;
$types_str="";
}
$types[] = $row['name'];
$d_array[] = $row['description'];
$temp++;
}
echo "<h1>".implode("<br />",$types_str_array )."</h1>";
You could do something like this:
<?php
//sample array
$types = array("John", "Doe", "Bar", "Baz", "Stock", "Overflow", "Meta" );
//Count the number of elements in $types
$types_count = count($types);
//Use $foo1, $foo2, $foo3 as the output array names
$out_types_count = 1;
$out_types_arr = "foo".$out_types_count;
for($i=1;$i<=$types_count;$i++){
$out_types_arr[] = $types[$i];
if(($i%5) == 0){ // if we $i == 5,10,15 etc,
$out_types_count++; // use $foo2
$out_types_arr = "foo".$out_types_count;
}
}// for loop ENDS
//Echo all the output
for($i=1;$i<=$out_types_count;$i++){
for($j=0;$j<=5;$j++){
echo $out_types_arr.$i[$j];
}
echo "<br />".PHP_EOL;
}
?>
P.S. Code has some errors & minor not-desired output. Because OP has got the answer he wanted, so I am gonna correct it later, from home.
How can I assign query result into array elements?
This is my code:
include('db.php');
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Database connection error");
mysql_select_db($dbname);
$query = "select * from test where value=20";
$result = mysql_query($query);
$vegetable_list = array('$rice', '$wheat', '$potato', '$pulses');
$i = 1;
while($row_result = mysql_fetch_row($result))
{
??????? = $row_result[$i];
$i++;
}
How can I assign the query result into the array? Let's say:
$rice = $row_result[1];
$wheat = $row_result[2];
$potato = $row_result[3];
How I can assign the values automatically?
Let try:
$vegetable_list= array('rice','wheat','potato','pulses'); //no $ symbol
while($row_result=mysql_fetch_row($result))
{
foreach($vegetable_list as $k => $v)
${$v} = $row_result[$k + 1]; //I think mysql_fetch_row should indexing from 0 -> n (not from 1)
}
Ok not sure but seems like you have a 150column x 20rows table that you want to convert into a two dimensional array. It is as simple as this:
$data = array( );
while( $row = mysql_fetch_assoc( $result ) )
{
// at this point, $row contains a single row as an associative array
// keys of this array consist of column names
// all you need to do is append $row to $data
$data[ ] = $row;
}
// $data is a two dimensional array
// $data[ 0 ] contains 1st row
// $data[ 1 ] contains 2nd row
// ...
// $data[ 0 ][ 'rice' ] contains rice column value for 1st row
// $data[ 0 ][ 'wheat' ] contains wheat column value for 1st row
// ...
// $data[ 1 ][ 'rice' ] contains rice column value for 2nd row
// $data[ 1 ][ 'wheat' ] contains wheat column value for 2nd row
// ...
// and so on
var_dump( $data );
Edited the code.
Here:
include('db.php');
$conn=mysql_connect($dbhost,$dbuser,$dbpass) or die("Database connection error");
mysql_select_db($dbname);
$query="select * from test where value=20";
$result=mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$vegetable_list= array( array () );
$rcols = mysql_query("SHOW COLUMNS FROM test");
if (!$rcols) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
$i = 0;
$j = 0;
if (mysql_num_rows($result) == 0) {
echo "No rows found.";
} else {
while ($row = mysql_fetch_assoc($result)) {
while ($cols = mysql_fetch_assoc($rcols);) {
$vegetable_list[$i][$j] = $row[$cols['Field']];
$i++;
}
$j++;
}
}
} else {
//some error message
}
use switch case :
$i=1;
while($row_result=mysql_fetch_assoc($result))
{
switch($i) {
case 1 : $rice = $row_result[$i]; break;
case 2 : $wheat = $row_result[$i]; break;
}
$i++;
}
or you can do this :
$i=0;
$vegetable = array("rice", "wheat", "potato");
while($row_result=mysql_fetch_assoc($result))
{
$idx = 0;
foreach($row_result as $result){
${$vegetable[$i]}[$idx] = $result;
$idx++;
}
$i++;
}
then try to
var_dump($rice);
you should get array of your specific column.
The first thing is that, you dont need to make array element as variable.
You can simply write without dollar sign like : $rice as rice and so on.
$vegetable_list= array('rice', 'wheat', 'potato', 'pulses');
Now execute Select query to get the data from database
$query = "select * from test where value=20";
$result = mysql_query($query);
make while loop
while($row_result=mysql_fetch_row($result))
{
foreach($vegetable_list as $k => $v)
${$v} = $row_result[$k + 1];
from 0 -> n (not from 1)
}