I want to get data from database using session of loggedin user in my website so he can see his profile with all of his data like name,country,city and address. But code which I am using is not working "SELECT * FROM login WHERE username = $_SESSION[user]" it's not giving me any data but when I replace it with this "SELECT * FROM login WHERE passowrd = $_SESSION[pass]" it works fine but it gives all data from database instead of only session or user who is loggedin please tell me the solution
here is the full code:
<?php
if(!isset($_COOKIE['loggedin'])){
header("location:index.php");
}
session_start();
if(!isset($_SESSION['user'])){
header("location: index.php");
}
else {
?>
<?php
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM login WHERE username = $_SESSION[user]")
or die(mysql_error());
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Country</th>
<th>City</th>
<th>Address</th>
</tr>";
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);}
?>
You have a lot of mistakes, mate. Let me try to give you a few advices:
Instead of:
"SELECT * FROM login WHERE username = $_SESSION[user]"
you need something like:
"SELECT * FROM login WHERE username = '".$_SESSION[user]."'"
You need the apostrophes around the username.
Make sure that $_SESSION[user] exists and really holds the username.
Never write queries like SELECT *, because that's not a good practice. The best practice is to select only the columns you really need. It is safer and more economical if we talk about memory usage. So instead of SELECT * use SELECT col1, col2, col3.
Try to obfuscate your password. If somebody breaks through your database he will be able to steal the identity of any users. Read more here and here. Do not forget about rainbow tables either if you are thinking about using something as simple as MD5.
Escape your queries to prevent SQL injections.
Related
I am passing over a factory operations system to a new support team and I am writing a guide for that.
It has a VERY simple DB section tucked inside and I just want very basic set of procedures for demonstration to the team who are very IT literate but do not have any DB or PHP experience.
I have finished most of the guide but having a bit of a problem with a simple Quantity update procedure.
Be clear - I have no problem doing it but I have searched and searched for a simple answer and also everything I do seems just far more complex than it needs be. Can anyone assist with simplicity !
As the base exampler I am using the well tried
<?php
$con=mysqli_connect('localhost', 'bbbbbb', 'bbbbb', 'bbbbbbl') or die(mysql_error());
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM orders_products");
echo "<table border='1'>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Quantity</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['products_id'] . "</td>";
echo "<td>" . $row['products_name'] . "</td>";
echo "<td>" . $row['products_quantity'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
which gives a simple table at the level I need
NOW all I want to demonstrate is how to update some or all of the Product Quantities in the list back to the MYSQL database. BUT AS SIMPLY AS POSSIBLE Without using individual "Edits" for each row. Apologies if this is too low level for you chaps !
NOTE: Edited to improve secrurity, but this does NOT negate the need for prepared statements to prevent other SQL injection attacks.
Wrap
<form method='POST' action='?'> around the table.
Replace
echo "<td>" . $row['products_quantity'] . "</td>";
With
$iProctId = $row['products_id'];
$iQuantity = $row['products_quantity'];
echo "<td>";
echo "<input type='text' name='product[{$iProductId}]' value='{$iQuantity}'/>";
echo "</td>";
In your script:
foreach( $_POST['product'] as $iProductId => $iQuantity ) {
mysqli_query( $con,"
UPDATE
orders_products
SET
products_quantity = ".(int)$iQuantity."
WHERE
products_id = ".(int)$iProductId."
");
}
Disclaimer
This script is simple, but not safe! To get it safe: mysqli_real_escape_string and mysqli_prepare
Enjoy :)
I have a table with arrays pulling information from a database, I have linked the fix to be a hyperlink "click me for fix" I have entered the link to send the variable to a php that will use $GET to echoe the information.
code below , i am new to php and been racking brains . the only out put i get is Welcome . (done welcome to test if information was being passed)
<div id=list>
<?php
// Create connection
$con=mysqli_connect('172.16.254.111',"user","password","Faults"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//where statement in the sql syntax will select where in db to get infor, use AND to add another condition
$result = mysqli_query($con,"SELECT * FROM Fixes WHERE Product='Serv1U' AND Fault_type='Broadcast Manager'"); //this creates a variable that selects the database
//below is the echo statment to create the results in a table format, list collumn titles
echo "<table id=tables border='1'>
<tr>
<th>Products</th>
<th>Fault_type</th>
<th>Fault_Description</th>
<th>Fix</th>
</tr>";
//below is script to list reults in a table format, $row [row name on table]
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Product'] . "</td>";
echo "<td>" . $row['Fault_type'] . "</td>";
echo "<td>" . $row['Fault_Description'] . "</td>";
echo "<td>Click for Fix</td>"; //this is how you link into an echo, alsothe id=" hopefully means i can send ID information.
}
echo "</tr>";
echo "</table>";
// below closes the coonection to mysql
mysqli_close($con);
index.php:
Welcome <?php echo $_GET["Fix"]; ?>.
I'm lost. Any help is appreciated.
Thanks
?>
Is it just a typo here? $GET must be $_GET.
And it should be $row['Fix'] not $rows['Fix']! Note the 's'!
I'm able to display what I have in my table with the code below, but as you can see in the code I'm linking the rows to a new page, and on that page I'm trying to display the rest of the rows, which I have in the same table.
I mean, I have cols ID, photo, Firstname, Lastname, Age, StreetAdd, PhoneNum, EmailAdd in the table. I'm displaying only rows photo, Firstname, Lastname on the first page.
So what I'm trying to do is when the user clicks on the First name , which I displayed from the database, he will be redirected to the new page and see the rest of the info. How do I do it?
This is the PHP page which displays the three cols. I can display the rest of the cols on a new page but it's displaying all the info in the row. I want to display the individual info for each user, not the whole list. A possible example would be eBay. When you search for items, you won't see the full description until you click on the picture or the title.
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("simple_login", $con);
$result = mysql_query("SELECT * FROM test ");
echo "<table align='center' bgcolor='#F9F0F0' border='0' cellspacing='0'>
<tr>
<th><font color='red'>Firstname</font></th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td><a href='send.php'><img src='".$row['photo']."' \" width=\"150px\" height=\"150px\" /></a><br><br><br>";
echo "<a href='send.php'><td align='center' style='vertical-align:text-top' width='200px'>" . $row['Firstname'] . "</td>";
echo "<td align='center' style='vertical-align:text-top' width='200px'>" . $row['Lastname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
On you have put a text level element a inside a block level element td the cell where first name is shown. Also you didn't close a tag there. correct form is this.
echo "<td align='center' style='vertical-align:text-top' width='200px'>";
echo "<a href='send.php'>" . $row['Firstname'] . "</a></td>";
To get the same user bio on the send.php you need to pass the primary key for this row. For examle if the primary key is id you pass it send.php in query string.
echo "<a href='send.php?id=".$row['id']."'>" . $row['Firstname'] . "</a></td>";
Now in the send.php use $_GET['id'] to get the primary key and use it to retrieve the user bio from db.
But make sure you escape parameters you pass to sql database. Dont use those variables directly! See Nullpointer's answer
Update 1:
When you get the primary key of a row just invoke a SELECT * with LIMIT 1
$pkey = mysql_real_escape_string($_GET['id']);
$sql = "SELECT * FROM test where id='$pkey' LIMIT 1";
/* Run this sql */
to display individual info for each user you can use where close in query like
SELECT * FROM test WHERE user = bla
Warning
your code is vulnerable to sql injection you need to escape all get and post and the better approach will be using Prepared statement
Good Read
How to prevent SQL injection in PHP?
Are PDO prepared statements sufficient to prevent SQL injection?
Note
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So use either PDO or MySQLi
Good read
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
Pdo Tutorial For Beginners
This should be your first page
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("simple_login", $con);
$result = mysql_query("SELECT * FROM test ");
echo "<table align='center' bgcolor='#F9F0F0' border='0' cellspacing='0'>
<tr>
<th><font color='red'>Firstname</font></th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td><a href='send.php'><img src='".$row['photo']."' \" width=\"150px\" height=\"150px\" /></a><br><br><br>";
echo "<a href='send.php?".$row['id']."'><td align='center' style='vertical-align:text-top' width='200px'>" . $row['Firstname'] . "</td>";
echo "<td align='center' style='vertical-align:text-top' width='200px'>" . $row['Lastname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Now send.php should be
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("simple_login", $con);
$sql = "SELECT * FROM test where id = " . $_Get['id'] ;
$result = mysql_query($sql);
//then display the result here
?>
hope this helps
Basicaly having issues setting up a webpage which will taken in a student key entered by the user. This will then parse the student key to another file which will run it against a mysql backend to see what records this student already has. But can not get it working for the life of me please help I'm still a newb at this.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("support_log", $con);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like '$_POST[stkey]'");
$result2 = mysql_query($result) or die("Error: " . mysql_error());
if(mysql_num_rows($result2) == 0){
echo("no records found");
} ELSE {
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Surname</th>
<th>Year Group</th>
<th>Student Key</th>
<th>Issue</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['First_Name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['year_group'] . "</td>";
echo "<td>" . $row['stkey'] . "</td>";
echo "<td>" . $row['issue'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close($con);
?>
After changing my where statement to:
WHERE student.STKEY like '$_POST[stkey]'");
I am no longer reciving errors from PHP but now recieving the error Query was empty which is part of my code to detect if there is no results. Though I have tested that query in phpmyadmin and it spits out results. From looking at the code does anyone have any solutions? I have also checked the parse by running an echo on the post command to ensure the data being entered was correct.
Edit: Got rid of the whole result2 check now throwing a:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\stkey_submit.php on line 24
Try $_POST['stkey'] instead of $_POST[stkey]
EDIT : if you use it in a query, it would be preferable to do :
$stkey = mysql_real_escape_string($_POST['stkey']);
$sql = "SELECT ....... like '$stkey'";
mysql_query($sql);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like " . $_POST["stkey"]);
How about storing the value of stkey on a variable before including it on the query?
$stkey = $_POST['stkey'];
$result= mysql_query("SELECT student.first_name, student.surname,
student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY LIKE '%$stkey%'");
You might also want to use MySqli or PDO instead of the MySql database API. Take a look at this post from Nettuts: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
I posted a couple days ago and I could not insert an additional record into a MySQL database I setup. I corrected the syntax, but the database will not update again. Basically, I have a couple forms in HTML that carry sessions over to the next pages until the PHP is processes on the final page to INSERT into the database. It worked twice (I have 2 records in the database now), but it won't insert any additional records. It worked fine a couple days ago. The only changes I made to anything was that I added a search feature that accesses the same database with the same user, but the connection is closed at the end of that script as well. Here is the code I am using to INSERT into the database (I know it isn't the best coding job, I'm still learning).
<?php
$con = mysql_connect("localhost","my_username","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dgibbo1_imaging", $con);
// Here too, please mysql_real_escape_string() all parameters
mysql_query("INSERT INTO imaging (os,MAC,Model,AntiVirus,Browser,Email,Connectivity,Sound,Ports) VALUES ('".$_SESSION['imaging2']."','".$_SESSION['imaging3']."','".$_SESSION['imaging4']."','".$_SESSION['antivirus']."','".$_SESSION['browser']."','".$_SESSION['email']."','".$_SESSION['connectivity']."','".$_SESSION['sound']."','".$_SESSION['ports']."')");
OR die("Could not update: ".mysql_error());
mysql_close($con);
?>
The name of the database is imaging. The columns are setup as:
id (This is the primary key field)
os
MAC
Model
AntiVirus
Browser
Email
Connectivity
Sound
Ports
I just find it odd that it inserted records without any problems until I tried it again today. Is it possible that it has something to do with my code for the search?
The search is a simple form on another page and processes this form:
<?php
$con = mysql_connect("localhost","my_user","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dgibbo1_imaging", $con);
// Always escape parameters injected into SQL queries
$result = mysql_query( "SELECT * FROM imaging WHERE MAC LIKE '%"
. mysql_real_escape_string ( $search, $con )
. "%'"
);
echo "<table border='1'>
<tr>
<th>MAC</th>
<th>Model</th>
<th>AntiVirus</th>
<th>Email</th>
<th>Browser</th>
<th>Connectivity</th>
<th>Sound</th>
<th>Ports</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['MAC'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['AntiVirus'] . "</td>";
echo "<td>" . $row['Email'] . "</td>";
echo "<td>" . $row['Browser'] . "</td>";
echo "<td>" . $row['Connectivity'] . "</td>";
echo "<td>" . $row['Sound'] . "</td>";
echo "<td>" . $row['Ports'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Meanwhile, the search will pull up the 2 existing records successfully every time, but I can't add new records and I'm wondering if it has something to do with this.
Thanks for any suggestions. I know my syntax probably isn't the best, so any suggestions from this site are always appreciated.
Try creating a separate php file and hard coding the values into it. Run that and see what happens. your search form shouldnt interfere with another form.
edit any errors when using the form? any errors when inserting to another table?
I saw your post, and it all looks "right". What I'd suggest is to add some logging instead of DIE and look at what MySQL is saying about those insert statements:
$sql = "INSERT INTO imaging ....";
mysql_query($sql);
if(mysql_errno()) {
$message = mysql_error() . "\n" . $sql . "\n";
$fp = fopen('c:\mylogifle.txt', 'a');
fwrite($fp, $message);
fclose($fp);
}
AND...as everyone has mentioned, encode those strings - assuming that the SQL is actually being executed, and you "know" it works, there's a very high possibility that some punctuation in one of the values is interfering with the SQL, like an unexpected comma somewhere that confuses MySQL