Benjamin Lawson Benjamin Lawson - 7 months ago 11
SQL Question

How to store the value of a SQL box into a PHP variable

I want to select the data and then store it's information inside of a variable. I feel this is very simple but I can't seem to get it to do it. When I run the below code the result is blank.

Thanks for any help.

$sql = "SELECT `$dateName` FROM `$user` WHERE hour=1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$x = $row["`$dateName`"];
echo $x;
}
}


Here is my Create Table code:

/* CREATE TABLE FOR NEW USER */
$sql = "CREATE TABLE `$newUser` (
hour INT(6) NOT NULL
)";
/* CHECK CREATION */
if ($conn->query($sql) === TRUE) {
} else {
echo "Error creating table: " . $conn->error . ".<br><br>";
}

/* ADD TABLE FOR TODAYS DATE */
$sql = "ALTER TABLE `$user`
ADD `$dateName` text";

if ($conn->query($sql) === TRUE) {
echo "Todays Date entered!";
} else {
echo "Date already Exists" . "<br><br>";
}

Answer

$x will always be empty because of the ` you're adding to the key when you access $row:

$x = $row["`$dateName`"];
           ^         ^ remove ticks (You can also remove ")