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'];
Grant
  • 2,413
  • 2
  • 30
  • 41

1 Answers1

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']; 
}
Grant
  • 2,413
  • 2
  • 30
  • 41
  • thanks, it's work now. So, the issue was with COUNT(*)... didn't think about it at all – Serghei Pogor Apr 03 '18 at 14:24
  • Just create an alias instead of selecting just COUNT(*), then its easy to access that in the while loop – Grant Apr 03 '18 at 14:25
  • **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: https://www.acunetix.com/websitesecurity/sql-injection/ Use PDO or prepared statements instead. – Grant Apr 03 '18 at 14:28
  • thanks for your advice, it's for a local server, no one has access except admin – Serghei Pogor Apr 03 '18 at 14:32