简体   繁体   中英

Using PHP variable to fetch data from mysql

I have a daily question quiz page and I have two database tables with the following names:

1) qbank 2) users_log

Now once the user submits the answer, it takes the user to the grade.php where I access if he/she answered the question correctly. My problem is the following code:

$sql = ("SELECT * FROM users_log WHERE username = '$username_wanted'");
$result = $conn->query($sql);
            if ($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                    $myuser = $row["username"];
                    echo $myuser;
                    echo "It found the user";
                    $mycolumn = $row_y[$_POST['question-id']];
                    echo $mycolumn;
                                        }
            }       

What I would like to do is to select that COLUMN from "users_log" TABLE where the COLUMN name is equal to the question-id from "qbank" table, where the user submitted in the previous page.

Let's just say I define a variable like such:

$questionID = "001"

What is the correct way of fetching with that variable:

$mycolumn = $row_y[$questionID];

Thanks, oliver_foxx

Your must construct a query like this (if i understood correctly)

$sql = "SELECT username, ".$_POST['question-id']." FROM users_log WHERE username = '".$username_wanted."'";

Of course there are some issues here but there are beyond the scope of this question. You may wanna research on these:

1) You are vulnerable to sql injection

2) I'm not very confident your sql structure is a good one. Seems like you have a column for each question; that sounds terribly denormalized

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM