I am trying to access the name field in the database through this code. But everytime it gives me "Illegal string offset error". I don't know the correct syntax needed inside second bracket of product_array.
$qry = "SELECT * FROM Products ORDER BY Product_Id ASC";
$result = mysqli_query($con,$qry);
$product_array = (array) $result->fetch_assoc();
mysqli_close($con);
if (!empty($product_array)) {
foreach($product_array as $key=>$value){
echo $product_array[$key]['Name'];
}
}
?>
fetch_assoc() only fetches one row - iterating this row gives you column values (single string, number, ...). And you try to access Name index on such value, which leads to error.
You need to use $product_array = $result->fetch_all(MYSQLI_ASSOC); to get iterate all results.
Also instead of $product_array[$key]['Name'] you can use $value['Name'].
mysqli::fetch_assoc does not return a multi dimensional array rather a 2d row from the database (only one), so, if you have the following fields / data for example;
name abc
date 01-01-2018
Using a query and fecth_assoc will return an array such as;
[ 'name' => 'abc', 'date' => '01-01-2018' ]
So, using foreach, you can do the following;
foreach ($product_array as $key => $value)
{
// Example printing; name = abc
echo "{$key} = {$value}";
// Example prining; abc
echo $product_array[$key];
}
Related
I made a function in a CI model that first queries for the table to get its fields(because these fields will change dynamically over time,so I can't hard code a list of field names),and then when it gets the results of the first query, and builds a fields name list,it queries the table again to get the values belonging to one row or record.It then stores the second query result in an array,which is passed back to the controller.Here is the complete function that performs these steps:
public function getAssetFeatures($as_id)
{
$data = array();
//this sql query gets the field names from the table I want to query.
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".DATABASE."' AND TABLE_NAME = 'as_features';";
$query = $this->db->query($sql);
$count = 0;
foreach($query->result_array() as $k)
{
foreach($k as $kk=>$v)
{
if( $v != "as_features_id" &&
$v != "as_id" &&
$v != "cid" &&
$v != "lot_size" )
{
$features_array[$count] = $v;
$count++;
}
}
}
$features_string = implode(",",$features_array);
//I got the field names, put them into an array, then concatenated them into a string, which I will use for the fields in the next query:
$sql = "SELECT $features_string FROM as_features WHERE as_id='$as_id'";
$query = $this->db->query($sql);
//mandatory rooms/features:
foreach($query->result() as $row)
{
foreach($row as $k=>$v)
{
$data["$k"] = $v; //build an associative array with the values of each field for the one row I am querying
}
}
return $data; // return the associative array.
}
At first I thought something was broken in my table or view,but as I kept repeating the same call to the model function by refreshing the page and entering the exact same values,I noticed that sometimes the code worked,and I wouldn't get the errors "undefined index".
So I outputted the results of the array with this code:
echo "<pre>";
print_r($asset['features']);
echo "</pre>";
...and the expected output, which only performs successfully sometimes, but not all the time, for the exact same operation using the exact same parameters, looks like this:
Array
(
[kitchen] => 1
[liv_area] => 0
[dining] => 1
[family] => 0
[bed] => 0
[bath] => 1
[half_bath] => 0
[parking] => 0
[car_storage] => 0
[pool] => 0
[miscellaneous] => 0
)
When the query returns a result set and then a populated array,my form works and looks normal.but,most of the time the query fails,and I get what looks like this:
The issue is with the following snippet of code:
foreach($query->result() as $row)
{
foreach($row as $k=>$v)
{
$data["$k"] = $v; //build an associative array with the values of each field for the one row I am querying
}
}
The way it works is that for every result which is returned it will overwrite $data with the relevant keys. However, because the $query->result() will return the row you want, then return false, the array essentially ends up being:
$data[] = false; i.e., set the whole array to false/empty.
If you change the loop to be, the code inside the loop won't be executed for the false value of $query->result():
while ($row = $query->result())
{
// your code
}
It's worth noting that if you're intending to return more that one row from this, it won't work as it will just overwrite the existing values.
Ok, the problem was my code, not the query. I was passing an encrypted as_id, but neglected to unencrypt it before constructing the select query. That's why it would work sometimes, and not others. For some reason MySQL allowed the encrypted as_id to match existing as_id of INT type. After performing the decrypt, the query results became predictable. This is something I wouldn't expect SO members to have divined. Thanks.
public function getAssetFeatures($as_id)
{
$as_id = $this->utilityclass->decryption9($as_id); // <- I had this commented out. In fact, I removed the line from my example code in the original post, because I didn't think it was important to the question. Not only was it important, it was the problem!
$data = array();
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".DATABASE."' AND TABLE_NAME = 'as_features';";
$query = $this->db->query($sql);
I've got an 2d array that stores data from my database table then puts it in a json file. And since I'm not calling my column names because it is dynamic, the array is adding it's incrementation (numbers) automatically with the table cell detail, I don't want this.
Here is the json file example
{"0":"1","Fix":"1","1":"Sunday, May 11, 2014","Date":"Sunday, May 11, 2014","2":"FT","Time":"FT","3":"Cardiff City","Home":"Cardiff City","4":"1-2","Score":"1-2","5":"Chelsea","Away":"Chelsea","6":"Cardiff City Stadium (27,716)","Stadium":"Cardiff City Stadium (27,716)"}
I attempted to remove it in php like this
//Select everything in table
$query = mysql_query("SELECT * FROM ".$tablename);
//Storing the data into one arrays witk the ey => value
while($r=mysql_fetch_array($query)){
//Store the data as a 2d array
$json[] = $r;
}
foreach ($json as $key => $value) {
# code...
if(preg_match('/[0-9]/', $key)){
unset($json[$key]);
}else{
}
}
//Display the JSOn data
$o = fopen($tablename.'.json', 'w');
echo fwrite($o, json_encode($json));
fclose($o);
use MYSQL_ASSOC as a second parameter of the mysql_fetch_array() function.
Hello guys I have seen a code with $row['columnname'].The code is
$myQuery = "SELECT * FROM information_schema.columns WHERE table_name = '$tabname'";
$re = mysql_query($myQuery);
while($row = mysql_fetch_array ($re)){
if(!empty ($row)){
$col_name = $row['COLUMN_NAME'];
$myQuery = "SELECT ".$col_name." FROM ".$tabname." WHERE sampleid='".$sid."'";
echo "<br>".$myQuery;
$reqq = mysql_query($myQuery);
$roww = mysql_fetch_array($reqq);
echo "<br>".$roww[$col_name];
}
}
My question is what is the use of $row[] in php?
Is it used to embed the column value like $row['columnname'] or just adding a variable like $row[$anyvariable].
That is called bracket notation. $row is an array, which has properties. In this case, it has named properties, so it is an associative array. An associate array has key/value pairs. It looks like this:
$myArray = [
'key' => 'value'
];
To echo the value of the property above, you would use echo $myArray['key'];
In the specific code you included, the property name is "COLUMN_NAME" and it has a value. The code assigns that value to the variable $col_name.
Here's another sample usage to help clarify all of this:
$people = [
'Susan' => [
'Age' => 24,
'Phone' => '555-123-4567'
],
'Jack' => [
'Age' => 27,
'Phone' => '555-9876-5432'
]
];
echo $people['Jack']['Age']; // 27
while($row = mysql_fetch_array ($re)){
This statement loops over all the rows returned in your result set $re and while looping, on every iteration you will get the current row as an array in your variable named $row, this name can be anything, it doesn't have to be $row necessarily.
Then
$col_name = $row['COLUMN_NAME'];
Is just reading $row as an array and picking up the value for the key COLUMN_NAME. This will be one of the columns that were returned by your query for each row of the result set. This also can be any name depending upon your query.
it is from mysql_fetch_array
it returns result array if your query/result was found, if not just FALSE instead
Like it says on the PHP site :
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
It's not variables that would go inside the $row[] , it's the column name that you have called in your SELECT query .
In your case, you have a SELECT query to return all the columns of a table. 'COLUMN_NAME' is in fact really the name of a column in the table of information_schema.column
mysql_fetch_array returns an array,
$row = [
'column_name' => 'column_value'
]
so the statement
$row = mysql_fetch_array ($re))
will fetches the column names from information_schema.columns that will be stored into $col_name.
$col_name = $row['COLUMN_NAME'];
for more read mysql_fetch_array
I have a table with blog column in it and i want to add values from a array, my problem is that i need to insert one full array value in one column. Here is what i am trying ...
foreach($title1->find('tr') as $song){
$name_a[] = $song->plaintext.'<br>';
}
and trying to enter this array in column
for($i=0, $count = count($name_a);$i<$count;$i++) {
$lyrics = array_push($name_a[$i]);
$songs_data_update = array(
'lyrics' => $lyrics,
'songs' => $song_name
);
try {
$STH = songs_data_update();
$STH->execute($songs_data_update);
}catch (PDOException $DBH){
die($DBH->getMessage());
}
}
i know this is wrong ... and its not working ... i want to add '< br >' in end of each row thats the reason i am making array to this. So how can i do this ... full array goes in one column
Use implode. E.g.
$lyrics = join('', $lyrics);
turns the Array $lyrics into a string consisting of all its elements concatenated.
I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);