3

Any idea how to include variable in $row[] mysqli_query?

what I've tried until now:

1

$result = mysqli_query($connection, "SELECT ".$var." AS Variables, COUNT(*)  FROM data GROUP BY '$var'"); 
while($row = mysqli_fetch_array($result)) {
    echo $row['Variables'];
    echo $row['COUNT(*)']; 
}

2

$result = mysqli_query($connection, "SELECT '$var', COUNT(*)  FROM data GROUP BY '$var'"); 
while($row = mysqli_fetch_array($result)) {
    echo $row[$var];
    echo $row['COUNT(*)']; 
}

Also, I've tried all combination

echo $row[$var];
echo $row["$var"];
echo $row['$var'];
7
  • 4
    I really REALLY hope $var is not submitted by the user... Commented Apr 3, 2018 at 13:53
  • Please explain a bit more. Including a vaiable in $row is what you have been doing in $row[$var] Commented Apr 3, 2018 at 13:54
  • Anyway, the first one is good (except for the risk of injection), just group by Variables instead and add an alias for the count, so you can use that as an index for $row. Commented Apr 3, 2018 at 13:57
  • both codes I wrote is not working, group by Variables not returning anything Commented Apr 3, 2018 at 14:14
  • 1
    Don't build SQL queries by string concatenation. It is error-prone and vulnerable to SQL-injection. Use prepared statements. Commented Apr 3, 2018 at 14:25

1 Answer 1

2

Try this:

$result = mysqli_query($connection, "SELECT ".$var." AS Variables, 
COUNT(*) AS count FROM data GROUP BY '$var'"); 
while($row = mysqli_fetch_array($result)) {
    echo $row['Variables'];
    echo $row['count']; 
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, it's work now. So, the issue was with COUNT(*)... didn't think about it at all
Just create an alias instead of selecting just COUNT(*), then its easy to access that in the while loop
NB: You have a GAPING SECURITY HOLE in your SQL statement, you need to ensure that a user cannot inject code into your SQL query by manipulating the $var variable. SQL Injection: acunetix.com/websitesecurity/sql-injection Use PDO or prepared statements instead.
thanks for your advice, it's for a local server, no one has access except admin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.