Using PHP variables as name of table in MySQL - php

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>Edit | <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

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

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!

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";

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";

Related

How to get the selected row from a link to a new page

Hello what I want is to get the same $typeValue which I am displaying in a message and then display the data.
In the first page the code that I am display the message with a specific $typeValue is the below
//ALERT SYSTEM
$query2 = mysql_query("SELECT username, typeValue FROM sensors WHERE (sensorValue < min OR sensorValue > max) AND doctorStatus='0'");
$query3 = mysql_query("SELECT username FROM sensors WHERE (sensorValue < min OR sensorValue > max) AND doctorStatus='0'");
//$row3 = mysql_fetch_array($query3);
while($row = mysql_fetch_array($query2))
{
while($row3 = mysql_fetch_array($query3))
{
$p1 = mysql_num_rows(queryMysql("SELECT * FROM connected
WHERE username='$row3[0]' AND friend='$username'"));
$p2 = mysql_num_rows(queryMysql("SELECT * FROM connected
WHERE username='$username' AND friend='$row3[0]'"));
if (($p1 + $p2) > 1)
{
$alert_message= " <b><font color=red><p align='center'>User " . $row['username'] . " Has A Health Problem with his/her ".$row['typeValue']."</font></b>";
$link_address = "health_problem.php?view=".$row['username']."&typevalue=".$row['typeValue'];
?>
<?php echo $alert_message; ?>
<?php
}
}
}
And the code of the other page which I want to display this data
<?php
/**
* #author Nick Bourlai
* #copyright 2015
*/
include_once 'header.php';
$result = queryMysql("SELECT * FROM patient WHERE username='$username'");
if(mysql_num_rows($result))
{
$query = "UPDATE sensors SET status='1' WHERE status ='0' AND username='$username'";
mysql_query($query)or die(mysql_error());
}
else
{
$query = "UPDATE sensors SET doctorStatus='1' WHERE doctorStatus ='0' AND username='$view'";
mysql_query($query)or die(mysql_error());
}
$con = mysqli_connect('localhost','root','smogi','project');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$view = ($_GET['view']);
$username2 =$_SESSION['username'];
$typeValue = ($_GET['typeValue']);
$sql="SELECT typeValue,unit,sensorValue,datetime FROM sensors WHERE username='$view' AND typeValue='$typeValue'";
$result = mysqli_query($con,$sql);
echo $view;
echo $typeValue;
echo "<table>
<tr>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr> <b>Type: </b>";
echo stripslashes($row['typeValue']) . "<br/><b>Unit: </b>";
echo stripslashes($row['unit']) . "<br/><b>Value: </b>";
echo stripslashes($row['sensorValue']) . "<br/><b>Date: </b>";
echo stripslashes($row['datetime']) . "<br/>";
echo "--------------------------------------------------------------------------------------------------------------";
echo "<br/></tr>";
}
echo "</table>";
?>
So what I want is to get from the clicked link the specific row and display the data of this row in the other page.
#Fred-ii- by mistake i switch my language in the keyboard and you answer was correct , about the small V in the word please write it as an answer in order to accept it
As per requested:
Your GET value is using an lowercase v in the URL
health_problem.php?view=magda&typevalue=Temperature, rather than an uppercase V in relation to typeValue in the GET array $_GET['typeValue']
health_problem.php?view=magda&typeValue=Temperature
Variables are case-sensitive.
Plus, on top of what has already been stated by myself in comments, that different MySQL APIs do not intermix with each other. Use the same MySQL API from connection to query.
Footnotes:
Consider using mysqli with prepared statements, or PDO with prepared statements, they're much safer.
PHP variables and array keys are case sensitive. This line in your 2nd script
$typeValue = ($_GET['typeValue']);
should be
$typeValue = ($_GET['typevalue']);

What could be wrong with this code? variable is not passing between the pages. trying to retrieve image from db

here are two files,
LIST IMAGE:
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("wordgraphic");
$sql = "SELECT id FROM userdata ORDER BY id DESC LIMIT 1,1";
$result=mysql_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
$row = mysql_fetch_array($result);
echo $row['id'];
?>
<img src="imageView.php?image_id=<?php echo $row['id']; ?>" /><br/>
<?php
mysql_close($conn);
?>
</BODY>
</HTML>
And other file:
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("wordgraphic") or die(mysql_error());
if(isset($_GET['id']))
{
$sql = "SELECT imageType,image FROM userdata WHERE id=" . $_GET['id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["image"];
}
else
"error";
mysql_close($conn);
?>
The second file is showing an image if i provide a static id but variable is not passed among the page and second issue is that when i echo :
$sql = "SELECT id FROM userdata ORDER BY id DESC LIMIT 1,1";
$result=mysql_query($sql);
It is giving id of not the last inserted query but 2nd Last inserted query.
Please help !
For the first problem change
if(isset($_GET['id']))
to:
if(isset($_GET['image_id']))
and for second problem
edit your query likr this :
SELECT id FROM userdata ORDER BY id DESC LIMIT 1
or
SELECT id FROM userdata ORDER BY id DESC LIMIT 0,1
SELECT id FROM userdata ORDER BY id DESC LIMIT 1
omit the coma and 1 on the last part of your query.
or if you want you can do this.
SELECT id FROM userdata ORDER BY id DESC LIMIT 0,1

Get the data of specific user in PHP

Now I have created a login form with a session, what I need now that when the user login with his username and password, get his data such as name, about etc.. and put it in the welcome page.
Currently I have created this code but this code get all users data,
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("usersdata") or die(mysql_error());
$data = mysql_query("SELECT * FROM userid")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['Name'] . "</td> ";
Print "<th>Username:</th> <td>".$info['Email'] . " </td></tr>";
}
Print "</table>";
?>
I hope to find a way to do that. :D
Since you already created a login form with session then you get the data for the current logged in user by doing this:
$_SESSION['userid']: Should be filled in the login page.
$_SESSION['userid'] = $id
Learn more about the sessions: PHP Sessions W3schools
And then:
$query= mysql_query("SELECT * FROM `userid` WHERE `id` = '".$_SESSION['userid']."' ")or die(mysql_error());
$arr = mysql_fetch_array($query);
$num = mysql_numrows($query); //this will count the rows (if exists)
HTML
<html>
//...
<?php if($num > 0){ ?>
<table border="1" cellpadding="3">
<tr><td colspan="2" align="center">Your Info</td></tr>
<tr>
<td>Name: <?php echo $arr['Name']; ?></td>
</tr>
<tr>
<td>Email: <?php echo $arr['Email']; ?></td>
</tr>
</table>
<?php }else{ ?>
User not found.
<?php } ?>
//...
</html>
Although you should use the mysqli_ extension, rather than mysql_, you would want something like:
$result = mysql_query("SELECT * FROM userid WHERE username = '" . $username . "'")
or die(mysql_error());
if(mysql_num_rows($result) == 1) {
//Found the user
$row = mysql_fetch_array($result);
//Results can be accessed like $row['username'] and $row['Email']
} else {
//Too few or too many records were found
}
Note: I've used username='$username' as an example. It would be best to track the user's ID from the login process as the ID refers to a specific row.
$data = mysql_query("SELECT * FROM userid")
Should be
$data = mysql_query("SELECT * FROM userid WHERE Name='$selectedName'")
Of course you need to define $selectedName
I also recommend you read http://dev.mysql.com/doc/refman/5.0/en/select.html to learn about some fundamentals.
Your example code retrieves all users from the database and loops through the data using a while loop.
To get the user that has logged in you need to change your query that fetches the data.
I'm assuming you have a primary key in your table and know the id because the user already logged in.
$data = mysql_query("SELECT * FROM userid WHERE id={$userid}");
$info = mysql_fetch_array( $data );
echo $info['Name'];
$info will now contain all the user info for 1 user, you need to fill $userid with the actual id from the user that is logged in.

Onchange update database

I'm trying to make an page where you can select a value in a dropdown select box. When the selection is made it should update the database using the selected value.
I use 2 pages one including the html/javascript and one using php.
Currently when i select something nothing happens.
What am i doing wrong?
test.php
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
function updateDb() {
$.post("buh.php", $("#form").serialize());
}
</script>
</head>
<body>
<form id="form">
<?php
include 'Includes/database_connection.php';
$sql = "select * FROM sims ORDER BY phonenr asc" ;
$result = mysql_query($sql,$con);
echo "<select id='select' name='select' onChange='updateDb()'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['phonenr'] . "'>" . $row['phonenr'] . "</option>";
}
echo "</select>";
?>
</form>
</body>
And buh.php
<?php
include 'Includes/database_connection.php';
$sql = "select * FROM sims ORDER WHERE phonenr='".mysql_escape_string($_POST["select"])."'" ;
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
mysql_query("UPDATE pairings SET sim_id='$id' WHERE unit_id='1'")
or die(mysql_error());
}
?>
You have something wrong with you SELECT query
$sql = "select * FROM sims ORDER WHERE phonenr='".mysql_escape_string($_POST["select"])."'" ;
^this ORDER here makes no sense
Either remove the word ORDER wich is a clause to order by a column, or assign it a column to order by with the correct syntax
SELECT * FROM tablename WHERE yourcolumncondition ORDER BY yourcolumntoorderby
Then I would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO
select * FROM sims ORDER ..You have added ORDER here wrongly in buh.php
$sql = "select * FROM sims ORDER WHERE phonenr='".mysql_escape_string($_POST["select"])."'" ;
$sql = "select * FROM sims ORDER WHERE phonenr='".mysql_escape_string($_POST["select"])."'" ;
remove order.

PHP - User Management Delete Problem

I am working on a custom content management system. I was instructed to do some changes, and this is what I need to do. I need to create a user management page which allows the administrator to delete (or disable his status) a user from the database.
This is my User Management Page:
<?php
$query = 'SELECT author_id, author_email as Email, author_name as Name
FROM authors
ORDER BY Name
LIMIT 0, 30';
$result = mysql_query($query);
?>
<table class="listing">
<thead>
<tr>
<td>Author ID</td>
<th>Author E-Mail</th>
<th>Author Name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $row = mysql_fetch_array($result); $i++) {
if ($i % 2 == 0) {
echo '<tr class="even">';
} else {
echo '<tr class="odd">';
}
echo "<td>{$row['author_id']}</td>";
echo "<td>{$row['Email']}</td>";
echo "<td>{$row['Name']}</td>";
echo "<td>X</td>";
echo '</tr>';
}
?>
</tbody>
</table>
This is my del-user.php page:
<?php
include('inc/config.php');
$title = 'Delete Individual User';
include('inc/db.php');
include('inc/header.php');
echo '<h2>Delete</h2>';
if (isset($GET['term'])) {
$query = "DELETE FROM authors WHERE author_id = {$GET['term']} LIMIT 1";
mysql_query($query) or die('Failed to delete user');
echo '<p>User Deleted</p>';
echo '<p>Back to <a href="manage-users.php">Manage Users </>.</p>';
} else {
echo '<p>Tried to Delete: "';
echo ($GET['term']);
echo '"</p>';
echo '<p>Nothing to Delete</p>';
}
include('inc/footer.php');
?>
I am new to PHP, but this is not working, the author_id value is not being passed to the other page, and it is being left empty. So I cannot delete anything from the del-users.php page.
I'm guessing that this is the problematic part:
echo "<td>X</td>";
Anybody knows why this is happening?
Several issues:
You send data like this:
del-user.php?term={$row['author_id']}
So that means that actualy $_GET['term'] contains the id.
You catch the value like this:
if (isset($_GET['author_id'])) {
$query = "DELETE FROM authors WHERE author_id = {$_GET['author_id']} LIMIT 1";
And it is not good, since $_GET['term'] contains the id, so you have to fix the lower one to look like this:
if (isset($_GET['term']))
$query = "DELETE FROM authors WHERE author_id = {mysql_real_escape_string($_GET['term'])} LIMIT 1";
Also you need to expand the select query, since you are not actualy fetching the author_id from the db:
$query = 'SELECT author_email as Email, author_name as Name, author_id
FROM authors
ORDER BY Name
LIMIT 0, 30';
Please, escape your variables before you trow them to the database...
http://php.net/manual/en/function.mysql-real-escape-string.php
Cheers
the problem is your query!
$query = 'SELECT author_email as Email, author_name as Name
FROM authors
ORDER BY Name
LIMIT 0, 30';
you are not selecting the author_id
You pass your user id in the url like this :
echo "<td><a href=\"del-user.php?term={$row['author_id']}\"
The you must GET term, not author_id :
$query = "DELETE FROM authors WHERE author_id = {$GET['term']} LIMIT 1";
And by the way, you should read about prepared query and sql injection ;)
use author_id in your query
<?php
$query = 'SELECT author_id, author_email as Email, author_name as Name
FROM authors
ORDER BY Name
LIMIT 0, 30';
$result = mysql_query($query);
?>

Categories