Reputation: 11
I want to use a PHP
variable ( $username
) as the name of the SQL
table I am creating.
I need to use this because in my webpage each user needs to have his own table where he can put data , When I try to select the data from the table doesn't work, I have tried a lot of times but it is not working, can you help me with this problem?
$result = mysqli_query($mysqli, "SELECT * FROM `$username` ORDER BY id DESC");
and
$sql= "SELECT * FROM `$username` ORDER BY data DESC";
Neither of these do not work , Can you please help me?
This is the code I have
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: login.php');
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header("location: login.php");
}
$sql= 'SELECT * FROM '.$username.' ORDER BY data DESC';
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<br/><br/>
<div>
<table align="center" width='100%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Data</td>
<td>Cantiere</td>
<td>Pranzo</td>
<td>Cena</td>
<td>Hotel</td>
<td>Macchina</td>
<td>Note</td>
<td>Edit/Delete</td>
</tr>
<?php
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['data']."</td>";
echo "<td>".$res['cantiere']."</td>";
echo "<td>".$res['pranzo']."</td>";
echo "<td>".$res['cena']."</td>";
echo "<td>".$res['hotel']."</td>";
echo "<td>".$res['macchina']."</td>";
echo "<td>".$res['note']."</td>";
echo "<td><a href=\"edit.php?id=$res[id]\">Edit</a> | <a
href=\"delete.php?id=$res[id]\" onClick=\"return confirm('Are you sure you
want to delete?')\">Delete</a></td>";
}
?>
</table>
</div>
</body>
</html>
and i get the error :
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in index.php on line 36
Upvotes: 1
Views: 81
Reputation: 2414
You need to concatinate your variable into your select statement, i.e.
$sql="SELECT * FROM ".$username." ORDER BY id DESC";
And
$sql="SELECT * FROM ".$username." ORDER BY data DESC";
Upvotes: 0
Reputation: 288
You should try something like this:
$result = mysqli_query($mysqli, "SELECT * FROM " . $username . " ORDER BY id DESC");
Because SQL does not know what $username is
This goes for both of the query's
As suggested by Loek:
Note that this answer (and the question) contain sql that easily be hijacked! Please prepare your statements before executing them!
Upvotes: 1
Reputation: 311
Try it like this
$sql= 'SELECT * FROM '.$username.' ORDER BY data DESC';
or
$result = mysqli_query($mysqli, "SELECT * FROM " .$username. " ORDER BY id DESC");
When you use a variable you need to use quotes
Upvotes: 1
Reputation: 1408
Try to add string concatenation:
$result = mysqli_query($mysqli, "SELECT * FROM " . $username . " ORDER BY id DESC");
and
$sql= "SELECT * FROM " . $username . " ORDER BY data DESC";
Upvotes: 0