问题
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]
.
回答1:
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
回答2:
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.
回答3:
it is from mysql_fetch_array
it returns result array if your query/result was found, if not just FALSE instead
回答4:
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
回答5:
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
来源:https://stackoverflow.com/questions/21423303/rowcolumn-in-php