Simple table query syntax error? - php

I hope someone here can help me see where this error is coming from.
I have a form with two fields: email and password. The form's action takes it to a php page that is supposed to
start a session
connect to a database via mysql
run a query and select a row in a table where the email field is similar to the email
submitted in the form.
At this stage it is incomplete, I only echo some of the fields at the end of the script to
see if it works.
I tested it and there was an unexpected end error that came up right at the last line; a bracket I left out. So I though there would be no other errors, but then when I tested it again I got this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#gmail.com' at line 6
#gmail.com is the last bit of the email I submitted.
Here is the code of the php (action) page:
<?php
session_start();
$_SESSION['sessionemail'] = $_POST['email'];
$_SESSION['sessionpassword'] = $_POST['password'];
$_SESSION['authuser'] = 0;
$dbhost = 'somewhere.com';
$dbuser = 'user';
$dbpass = 'pw';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn));
$query = 'SELECT
name, smacker, surname, sex, age, nationality, email
FROM
employee
WHERE
email = ' . $_POST['email'];
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>
I tried removed the first 5 lines and I still got the same error.
Somehow, when the php gets parsed, the browser reads the content of the email variable as if it is part of my php code. At least that's what I thought because the error I receive states that there is a problem with the syntax near "#gmail.com".
I hope someone can give me a clue!

You have an SQL injection, always apply mysql_real_escape_string() to any user-submitted or otherwise potentially tampered-with data before sending to a MySQL database.
Note the ' around the email variable.
$email = mysql_real_escape_string($_POST['email']);
$query = "
SELECT name, smacker, surname, sex, age, nationality, email
FROM employee
WHERE email = '$email'
";

<?php
session_start();
$_SESSION['sessionemail'] = $_POST['email'];
$_SESSION['sessionpassword'] = $_POST['password'];
$_SESSION['authuser'] = 0;
$dbhost = 'dedi147.cpt2.host-h.net';
$dbuser = 'medreunten_1';
$dbpass = 'AGqrVrs8';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn));
$query = "SELECT name, smacker, surname, sex, age, nationality, email FROM employee WHERE email = '" . $_POST['email']."'";
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>
try this, should work

Related

Can someone explain PHP SQL Select data to me?

I want to select the password data of a user so they can log in on my website (for a member only website). I have a hash of the password and the username written to a table called "users" upon account creation. I do not know how to select a row on the table, so I get the error when the code looks for, something?
I found this on w3, but I don't understand what each part of the code means.
I tried to edit the code so it would match my user case, but I don't know how to.
$servername ="127.0.0.1";
$dbusername = "root";
$dbpassword = "";
$dbname = "users";
//create connection to db
$conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
$sql = "SELECT id, username, password FROM users";
$result == $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row == $result->fetch_assoc()) {
echo $userid = $row["id"] && $serverpassword = $row["password"] && $serverusername = $row["username"];
}
} else {
echo "User Lookup Failed";
}
$conn->close();
You don't need to select all records from database and then iterate all of them to check correct user. Besides, you should only select user by username and password as below:
$sql = "SELECT id, username, password FROM users WHERE username = '".$serverusername."' AND `password` = '".serverpassword."' ";
Apart, you should use data binding instead of variable to avoid SQL injection.

How do I connect my website to a MySQL database?

Below is the code I have in my Sublime, but the database isn't being called.
<?php$username="root";
$password="changedpassword";$database="User";
$field1-name=$_POST['name'];
$field2-name=$_POST['password'];
$field3-name=$_POST['email'];
$field4-name=$_POST['sex'];
$field5-name=$_POST['school'];
$field6-name=$_POST['birth'];
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO create_user (name, password, email, sex, school, birth) VALUES('','$field1-name','$field2-name',
'$field3-name','$field4-name','$field5-name','$field6-name')";mysql_query($query);mysql_close();?>
Let's go through this step by step. First, here's your current code, tidied up to be readable:
<?php
$username = "root";
$password = "changedpassword";
$database = "User";
$field1_name = $_POST['name'];
$field2_name = $_POST['password'];
$field3_name = $_POST['email'];
$field4_name = $_POST['sex'];
$field5_name = $_POST['school'];
$field6_name = $_POST['birth'];
mysql_connect(localhost, $username, $password);
#mysql_select_db($database) or die("Unable to select database");
$query = "
INSERT INTO
create_user
(
name,
password,
email,
sex,
school,
birth
)
VALUES
(
'',
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
";
mysql_query($query);
mysql_close();
?>
I've made only two changes (tidied the whitespace, and used _name instead of -name, as PHP variables cannot contain hyphens), but it's already a big improvement. The code is no longer an eyesore. It does not have syntax errors, and it is readable. There are still, though, a large number of problems.
First, you see that we are inserting seven values into six columns. This will be a problem. Fix that by removing the first blank value:
$query = "
INSERT INTO
create_user
(
name,
password,
email,
sex,
school,
birth
)
VALUES
(
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
";
Now we have something that might actually work. It's painfully insecure, with massive potential for SQL injection attacks, and it won't work on the latest PHP because the mysql_ functions have been removed, but it might actually kind of work somewhere. You wouldn't want to put it into production, but for test purposes, we're getting somewhere.
MySQL is deprecated since PHP 5.6 and is insecure, use PDO or MySQLi instead.
Connecting with MySQLi
<?php
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
$field1_name = $_POST['name'];
$field2_name = $_POST['password'];
$field3_name = $_POST['email'];
$field4_name = $_POST['sex'];
$field5_name = $_POST['school'];
$field6_name = $_POST['birth'];
$query = mysqli_query($connection, "INSERT INTO create_user
(name, password, email, sex, school, birth ) VALUES
(
'$field1_name',
'$field2_name',
'$field3_name',
'$field4_name',
'$field5_name',
'$field6_name'
)
");
Use this and you will be good. I hope this has helped you!

migrating mysql to mysqli in ajax environment

First i would like to say thank you for letting me ask questions again. I know my previous question was a bit low level of knowledge. Today, I would like to ask if the principle of converting mysql to mysqli in ajax is same with html. Suppose this is my Connect.php
<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "765632";
$dbname = "student";
$link_id = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link_id));
?>
and my ajax.php is
<?php
//Connect to MySQL Server
include 'Connect.php';
mysql_connect($host, $dbusername, $dbpassword);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Escape User Input to help prevent SQL Injection
$first_name = mysql_real_escape_string(trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysql_query($query) or die(mysql_error());
//Generate the output
$searchResults = '';
if(!mysql_num_rows($result))
What are the changes should i made to convert it to mysqli without changing its logical scheme.
Did you mean this?
$link_id = mysqli_connect($host, $dbusername, $dbpassword);
//Select Database
mysqli_select_db($link_id, $dbname) or die(mysqli_error($link_id));
// Escape User Input to help prevent SQL Injection
$first_name = mysqli_real_escape_string($link_id, trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysqli_query($link_id, $query) or die(mysqli_error($link_id));
//Generate the output
$searchResults = '';
if(!mysqli_num_rows($result))

PHP Select fields from database where username equals X

im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.

can't perform SELECT query

My script is supposed to log the user into my database.
it does this by checking whether or not the username and password matches a row on the staff table.
if it is discovered that the username and password does exist it stores the username and password on the cookie.
The problem that I'm getting is that users are not being logged in.
It has been identified via the echo method that the following variables have the following values upon clicking the button
$row = 0
$username = whatever is in the username field on the form
this seems to indicate that there is something wrong with the query
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'the_shop';
mysql_select_db($dbname);
if(isset($_GET['submit']))
{
$username = $_GET['username'];
$password = md5($_GET['password']);
echo "$username + $password <br />";
// insert user into db
// $sql = "INSERT INTO `logindb`.`users` (`id`, `username`, `password`) VALUES (NULL, '".$username."', '".$password."');";
// echo $sql;
// $result = mysql_query($sql);
// getting user from db
$query = "SELECT Username, Password FROM staff WHERE `Username`='.$username.'";
$result = mysql_query($query)
or die(mysql_error());
$num=mysql_numrows($result);
echo $num;
if($num <= 0) {
echo "login not successful";
echo "$username";
}
else
{
$_SESSION['username'] = '$username';
$_SESSION['password'] = '$password';
//header("Location:Admin_Control_panel.php");
}
}
?>
For starters your $query has unwanted characters (.) in there.
"SELECT Username, Password FROM staff WHERE `Username`='.$username.'"
^ ^
Should be.
"SELECT Username, Password FROM staff WHERE `Username`= '$username'"
Without the dots.
This line:
$query = "SELECT Username, Password FROM staff WHERE `Username`='.$username.'";
Needs to be:
$query = "SELECT Username, Password FROM staff WHERE `Username`='$username'";
There is no need to concatenate the string since you're using double-quotes and PHP is parsing the $ values inside a double quoted string.
Your query should be:
$query = 'SELECT Username, Password FROM staff WHERE Username = ' . $username;
I suggest looking into PDO (PHP Data Objects) as an alternative to the method you are using and parameterising your variables.
http://php.net/manual/en/book.pdo.php
$query = "SELECT Username, Password FROM staff WHERE `Username`='$username'";

Categories