Bijan Kelley Bijan Kelley - 1 year ago 52
MySQL Question

PHP - AJAX and MySQL - Query error

In the last couple days I set up my own local web server and began to develop a prototype web application. This web application is simple for now. I have a dropdown list with names of MySQL tables and a div that will update with all of the rows of the selected table. Yes, the div properly updated when I tried a simple query to select * from table_name.

However, I'm bringing in AJAX now to add functionality to the dropdown list and the div will not update. I used the code from W3 but their query is different than mine, otherwise it does work with a query that doesn't use a variable as a table name. I've pinpointed the exact problem through trial and error and I have no idea how to fix it. (I've looked for the answer online already) The AJAX script uses a function that is called when an item on the dropdown list is selected. Once the item is selected the AJAX does its requests and then sends the variable to the php file. The php file has successfully grabbed the information but only when I do queries such as:

$sql = "select * from table_name where Price = '" . $q . "'";

The exact issue: I'm trying to use the variable as the table name and I've formatted the string every possible way I could think of but the string is just wrong. I keep getting the error "mysqli_fetch_assoc() expects parameter 1 to be mysqli_result" but I've been down this path before so I know this is because of the SQL query string. (I've also tried different mysqli_fetch functions)

Alright here is how my code looks just in case you need some insight, but I'm confident this is about the query.


function showUser(str) {
if (str === "") {
document.getElementById("playerList").innerHTML = "";
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("playerList").innerHTML = this.responseText;
};"GET", "getuser.php?q=" + str, true);



$q = intval($_GET['q']);

require 'conn.php';
$query = "SELECT * FROM $q";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
//echo with html formatting


I've tried formatting the query several different ways

$query = "select * from `$q`";

$query = "select * from `" . $q . "`";

$query = "select * from "$q"";

$query = "select * from " . $q . "";

$query = "select * from '" . $q . "'";

//I've even tried this, and it works but it's not dynamic because it's not using the variable!
$table = "table_name";
$query = "select * from $table_name";

Answer Source

Replace intval($_GET['q']); To $_GET['q'];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download