$row['column'] in PHP - php

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

Related

Illegal string offset 'Name' Error

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];
}

Associative array not storing first result from SQL

I have a database in MySQL and I'm using this query to select certain rows from it using PHP:
$q = "SELECT Number, Body
FROM boxes
WHERE Number BETWEEN '1' AND '4' ORDER BY Number ASC";
Then calling the query and initiating arrays:
$r = $mysqli->query($q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$array = array();
$content = array();
Then attempting to sort the results into an associative array where the 'number' is the key and the 'body' is the value.
while ($row = mysqli_fetch_assoc($r)) {
$array = array(
$content[$row['Number']] = $row['Body']
);
This works fine except it will not store the first value. This is the result of print_r($content);, missing the first row.
Array ( [2] => This is entry two [3] => This is entry three [4] => This is entry four )
I have tried running the SQL query within PHPMyAdmin and it returns all four rows as I would expect.
Does anyone have any ideas what I'm doing wrong?
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
You are getting first returned row by this line. You have to remove it and it will work properly.
mysqli_fetch_array and mysqli_fetch_assoc returning NEXT row on every call.

PHP get one row from an array based on a variables value

If i create an array from results returned in a mysqli query is there a way to select and use only one specific row from the array?
$info= array();
while($row = mysqli_fetch_assoc($query)) {
$info[] = array(
'id' => $row['id'],
'location' => $row['location']
);
}
How would i go about displaying only a single row from this array where the id equals a variable like $id?
In your loop you could just do something like:
if ($id == $row['id']) {
$info[] = $row;
}
However it would make more sense to me to just update your query.
SELECT cols FROM t1 WHERE id = :id
Using $id as a parameter.

Create dynamic associated array from database fields

I got a database with 2 fields: amount and name.
I want to get all the data from the database (40 rows) and create an associated array out of it like this:
$arr = array("amount" => "12", "name" => "John");
How is this done dynamically in PHP? I am stuck.
If you're using the mysql_* function, you can do the following to get one row at a time:
$res = mysql_query("SELECT amount, name FROM mytable");
while ($row = mysql_fetch_assoc($res)) {
var_export($row); // outputs array ( 'amount' => '12', 'name' => 'John', )
}
To get all rows in a single array:
$customers = array();
$res = mysql_query("SELECT amount, name FROM customers");
while ($row = mysql_fetch_assoc($res)) {
$customers[] = $row;
}
Well, if you run your query, e.g.
$result = mysql_query('SELECT amount, name FROM table');
you can loop over the result like that:
$values = array();
while(($row = mysql_fetch_assoc($result))) {
$values[] = $row;//$row will be like array("amount" => "12", "name" => "John")
}
and you will have an array of arrays.
Check out mysql_fetch_assoc if you want to fetch database rows as an associative array (the documentation comes with a good example, too).
$data = $pdo->query('SELECT amount, name FROM ...')->fetchAll(PDO::FETCH_ASSOC);
That's it in PDO. And if you're not using PDO, well, that's your problem then...

Two dimensional associative array in PHP

In my code I'm getting data (three columns) from a sql db and I want to store the rows in an associative PHP array. The array must be multi-dimensional because I want to use the row id from the database as a key so that i can fetch values like this:
$products["f84jjg"]["name"]
$products["245"]["code"]
I've tried using the following code but it doesn't work:
while ($row = mysql_fetch_row($sqlresult))
{
$products = array($row[0] => array(
name => $row[1],
code => $row[2]
)
);
}
Also, how should I reference the key if it is taken from a variable? What I want to do is:
$productName = $products[$thisProd]["name"];
Will this work?
This should do it, assuming row[0]'s contents is a unique identifier (else you could override a row):
while($row = mysql_fetch_row($sqlresult)) {
$products[$row[0]] = array(
'name' => $row[1],
'code' => $row[2]
);
}
You need to put quotes around the array keys, and you were creating an array of array of arrays.
Also note you could use mysql_fetch_assoc instead of mysql_fetch_row, which would give you the array keys as the column names, which would make this much easier/cleaner:
while($row = mysql_fetch_assoc($sqlresult)) {
$products[$row['myidcolumn']] = $row;
}
After you do this, the code you described would work.

Categories