Click here to Skip to main content
15,895,462 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
in the SQL SELECT, when we use $row["table name"], how can we use a PHP variable instead of string table name?

What I have tried:

<pre>
for ($i=1; $i <= 1000; $i++){
$sql ="SELECT * FROM SPC WHERE id='$i'";
$result = $con->query($sql);
$row = $result->fetch_assoc();
$panel = $row["Panel"];
}
//No problem to this point, I got what I wanted
//Now, can we make "Panel" as a PHP variable?, I tried this but it's not working
$prmetr = "Panel";
$panel = $row["<?php echo $prmetr; ?>"];
//or
$panel = $row['$prmetr'];
//not working too
<pre>
Posted
Updated 13-May-20 7:05am

Try
PHP
$row[$prmetr]


You should also used a prepared statement instead of concatenating strings to build your query:
PHP MySQL Prepared Statements[^]

And the fact that you enclose the id between quotes suggests that you defined a numeric field in your database using a string type; this is also a bad practice, you always should use the proper datatype.
 
Share this answer
 
Comments
Member 14819235 14-May-20 11:38am    
It works, thank you
You are going through a loop for all 1000 values of $id. That is incredibly wasteful of resources.

You'd get the same results with a single query something like:
SELECT * FROM SPC WHERE id BETWEEN 0 AND 1000 ORDER BY id
Then work with the results set in a loop.

Beyond that, as noted in solution 1, you should not have the quotes around your php variable value when it's used as an index.
 
Share this answer
 
v2
Comments
Member 14819235 14-May-20 11:38am    
I will try it, thank you so much
W Balboos, GHB 14-May-20 11:47am    
As a free bonus help: if you are using an indexed data type, like your $row[], you need to wrap it in curly braces if it's within a double-quoted text string.

Like this: $text = "My name is {$row['name']}";

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900