SQL Selecting Data with WHERE ". $variable ." - php

my question is:
I have an issue with my code (SELECTING data from MySql)
This is my code
<?php
$user_name = $_SESSION['user_name'];
$user_email = $_SESSION['user_email'];
echo $user_email;
$con = mysqli_connect("localhost", "root", "", "minehelp");
$id_query = mysqli_query($con, "SELECT user_name FROM users_en WHERE user_name = '" . $user_name . "' OR user_email = '" . $user_email . "';");
while ($row_id_query = mysqli_fetch_assoc($id_query)){
print($row_id_query['user_name']);
}
?>
I want to select data WHERE the "user_name is $user_name"
This is login system, that means the $_SESSION'user_name'
is part of my code and i can't remake it.
Thanks for every answer,
Jakubk-0

Should be looking similar to
$sql = "INSERT INTO users (NickName, PassWord, Email)
VALUES (:nick, :pass, :mail)";
$conn->prepare($sql);
$conn->execute(array(':nick' => $NickNaming, ':pass' => $PassWording, ':mail' => $Emailing));

You should use PDO::prepare
Prepares an SQL statement to be executed by the
PDOStatement::execute() method.
and PDO::execute
Execute the prepared statement.
So your prepare and execute would look like this:
$sth = $conn->prepare( 'INSERT INTO users (NickName, PassWord, Email)
VALUES (:nick, :pass, :mail)');
$sth->execute( array(':nick' => $NickNaming,
':pass' => $PassWording,
':mail' => $Emailing));

I tried to not use PDO :
$insert = mysqli_query($con,"INSERT INTO users (Nickname, PassWord, Email)
VALUES ('$NickName','$PassWording','$Emailing')");
That will work

Related

How to tell which query had an error? [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
I am trying to convert my mysqli database that was very vulnerable to PDO prepared statements. I think i almost got it since it actully inputs the registration data to the database but not to the other databases. So i think there must be some issues on those queries but i can't figure it out. Here below is my code.
<?php
session_start();
// DATABASE CONNECTION
$user = '****';
$pass = '****';
//CREATE CONNECTION
// $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$pdo = new PDO('mysql:host=localhost;dbname=****', $user, $pass);
// ASSIGN VARIABLE FROM FORM
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$password = password_hash($password, PASSWORD_BCRYPT);
// CHECK IF USER IS UNIQUE
$stmt = $pdo->prepare("SELECT username FROM users WHERE username = :name");
$stmt->bindParam(':name', $username);
$stmt->execute();
if ($stmt->rowCount() > 0) {
echo "That username already exist!";
} else {
//INSERT DATA INTO DATABASE
$sql = "INSERT INTO users ( username, password, email )
VALUES ( :username, :password, :email )";
$sql1 = "INSERT INTO stats (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
$sql2 = "INSERT INTO progression (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
$sql3 = "INSERT INTO powervalues (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
// EXECUTE AND PREPARE
$query = $pdo->prepare($sql);
$query1 = $pdo->prepare($sql1);
$query2 = $pdo->prepare($sql2);
$query3 = $pdo->prepare($sql3);
$result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
$result1 = $query1->execute(array( ':username'=>$username ));
$result2 = $query2->execute(array( ':username'=>$username ));
$result3 = $query3->execute(array( ':username'=>$username ));
//EXECUTE QUERY
if ($result && $result1 && $result2 && $result3) {
$_SESSION['Accountsucess'] = "Account has been added sucessfully.";
header("location: ../../index.php?page=index");
} else {
echo "Error database failure";
}
}
Instead of continually selecting various parts of information, once you have inserted the user in the users table, fetch the last insert ID and then use that in subsequent calls...
$sql = "INSERT INTO users ( username, password, email )
VALUES ( :username, :password, :email )";
$sql1 = "INSERT INTO stats (id, username)
VALUES (:id,:username)";
// EXECUTE AND PREPARE
$query = $pdo->prepare($sql);
$query1 = $pdo->prepare($sql1);
$result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
// Fetch id of new user
$id = $pdo->lastInsertId();
$result1 = $query1->execute(array( ':id' => $id, ':username'=>$username ));
Repeat this same logic for each of the other statements.

Basic signup form [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I have create a sign-up form which receives username, email and password.
I coded like this:
include_once 'sqlConnect.php';
$userName = $_POST['userName'];
$eMail = $_POST['eMail'];
$passWord = $_POST['passWord'];
$day = date("d-m-Y");
$time = date("h:i:sa");
$dbINSERTuser = 'INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('$userName', '$eMail', '$passWord', '$time')';
$result = mysql_query($dbINSERTuser);
if ($result) {
echo "New record created successfully";
}
else {
echo mysql_error($dbINSERTuser);
}
In the end, it gave me this error:
Parse error: syntax error, unexpected '$userName' (T_VARIABLE) in G:\XAMPP\htdocs\Project EVO 1.0\signup.php on line 17
I have been looking at this for hours and still not finding any solution. Please help!
PHP will evaluate variables values in the string, only when your string is wrapped with double quotes.
Change this:
$dbINSERTuser = 'INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('$userName', '$eMail', '$passWord', '$time')';
To this:
$dbINSERTuser = "INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('$userName', '$eMail', '$passWord', '$time')";
But be aware - this code is vulnerable to SQL injections!
UPDATE:
Learn how to use PHP's PDO and prepared statements to make you queries safe.
Just replace ' with " in your insert query
$dbINSERTuser = "INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('$userName', '$eMail', '$passWord', '$time')";
To prevent sql injection use
$dbINSERTuser = "INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('".$userName."', '".$eMail."', '".$passWord."', '".$time."')";
IN mysqli you can use like that way
<?php
$link = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$userName = $_POST['userName'];
$eMail = $_POST['eMail'];
$passWord = $_POST['passWord'];
$day = date("d-m-Y");
$time = date("h:i:sa");
$dbINSERTuser = "INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('".$userName."', '".$eMail."', '".$passWord."', '".$time."')";
mysqli_query($link, $query);
Read mysqli manual
you forgot to concat string
change
$dbINSERTuser = 'INSERT INTO user_info (Username, Email, Password, Time)
VALUE ('$userName', '$eMail', '$passWord', '$time')';
to
$dbINSERTuser = 'INSERT INTO user_info (Username, Email, Password, Time)
VALUE (' . $userName . ', ' . $eMail . ', ' . $passWord . ', ' . $time .')';
$dbINSERTuser = 'INSERT INTO user_info (Username, Email, Password, Time)
VALUE (''.$userName.'', ''.$eMail.'', ''.$passWord.'', ''.$time.'')';
Change as above
Try This.
<?php
$userName = mysql_real_escape_string($_POST['userName']);
$eMail = mysql_real_escape_string($_POST['eMail']);
$passWord = mysql_real_escape_string($_POST['passWord']);
$day = mysql_real_escape_string(date("d-m-Y"));
$time = mysql_real_escape_string(date("h:i:sa"));
?>

Input values aren't being stored in a MySQL database

I've created a simple login form. I'm not able to store user input values at the back-end. Here's the full code for your reference:
dp.php
<?php
$dbc = mysqli_connect('localhost', 'root', '', 'list') or trigger_error(mysqli_error());
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email_id'];
$password = $_POST['password'];
$query = "INSERT INTO login_list (first_name, last_name, email,password) VALUES ('$first_name', '$last_name', '$email','$password')";
mysqli_query($dbc, $query) or trigger_error(mysqli_error($dbc));
echo 'login created';
mysqli_close($dbc);
?>
remove single quote from php variable
$query = "INSERT INTO login_list (first_name, last_name, email,password) VALUES
($first_name, $last_name, $email,$password)";
if your data contain string that will put in "" or ''
$query = "INSERT INTO login_list (first_name, last_name, email,password) VALUES
('".$first_name."','".$last_name."', '".$email."','".$password."')";
i hope this will solve your problem if $_POST get correct data . you have to concat string at that time

Unable to locate sql error in php

Error message i've been recieving
Parse error: syntax error, unexpected 'INTO' (T_STRING) in D:\ServerFolders\Web\tokens\insert.php on line 17
Line 17
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
Full code
<?php
//Connect to DB
$con=mysql_connect(localhost,root, "",APROJECT) or die (mysql_error());
// Check connection
if (mysql_connect_errno()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
// escape variables for security
$Forename = mysql_real_escape_string($con, $_POST['Forename']);
$Surname = mysql_real_escape_string($con, $_POST['Surname']);
$Email = mysql_real_escape_string($con, $_POST['Email']);
$Username = mysql_real_escape_string($con, $_POST['Username']);
$Password = mysql_real_escape_string($con, $_POST['Password']);
$DOB = mysql_real_escape_string($con, $_POST['DOB']);
//SQL query to add data to DB
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB);
if (!mysql_query($con,$sql)) {
die('Error: ' . mysql_error($con));
}
echo "1 record added";
mysql_close($con);
?>
First of all, mysql_* is not supported anymore and advised to use PDO or mysqli_* instead.
You should put query into quotes;
$sql= "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
It may not work! Because you have to put values into single quotes. So better approach is using parameterized query.
For this time only I suggest using sprintf() function.
$sql= sprintf("INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s')", $Forename, $Surname, $Email, $Username, $Password, $DOB);
Try adding quotes
$sql= "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
$sql= INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB);
The above line needs to be a string and in one line (variables in strings which start and end in " can be directly written into it):
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) VALUES ($Forename, $Surname, $Email, $Username, $Password, $DOB)";
If you want it to be in multiple lines for better readability, you can use the nowdoc syntax with variables embeded in {}:
$sql <<<'EOD'
INSERT INTO users(Forename, Surname, Email, Username, Password, DOB)
VALUES ({$Forename}, {$Surname}, {$Email}, {$Username}, {$Password}, {$DOB})
EOD;
Last approach would be to concat the string with .:
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) " .
"VALUES (" . $Forename . ", " . $Surname . ", " . $Email . ", " . $Username . ", " . $Password . ", " . $DOB . ")";
See this reference: http://php.net/manual/de/language.types.string.php
On a side note, don't forget to escape your variables in your mysql query with mysql_real_escape_string to prevent SQL Injection!
$sql = "INSERT INTO users(Forename, Surname, Email, Username, Password, DOB) " .
"VALUES (" . mysql_real_escape_string($Forename) . ", " . mysql_real_escape_string($Surname) . ", " . mysql_real_escape_string($Email) . ", " . mysql_real_escape_string($Username) . ", " . mysql_real_escape_string($Password) . ", " . mysql_real_escape_string($DOB) . ")";
It looks like you're just missing some quote around your sql query.
Something like
$sql= "INSERT INTO `users`(`Forename`, `Surname`, `Email`, `Username`, `Password`, `DOB`)
VALUES (".$Forename.", ".$Surname.", ".$Email.", ".$Username.", ".$Password.", ".$DOB.")";
Should fix your error.
It's also worth nothing that mysql_query is depreciated and can be pretty unsecure. It might be worth looking at PDO preapred statements if this is something that's going to be used in production. Check out http://php.net/manual/en/ref.pdo-mysql.php and Dream in Code PDO

Form data not being sent to MySql database

Have a simple registration form that is being linked to a php file in order to send the info to a database but everytime i try it the data isnt showing up in the phpMyAdmin database??
<?php
$name = $_POST['name'];
$address = $_POST['address'];
$number = $_POST['number'];
$email = $_POST['email'];
$details = $_POST['details'];
$user="root";
$password="secure";
$database="darrenweircharity";
mysql_connect("localhost",$user,$password);
#mysql_select_db($database) or die ("Unable to select database");
$query = "INSERT INTO registrationdetails(name, address, number, email, details)".
"VALUES('$name', '$address', '$number', '$email', '$details' NOW())";
mysql_query($query);
mysql_close();
?>
Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Try with:
$query = "INSERT INTO registrationdetails(name, address, number, email, details)".
"VALUES('" . $name . "', '" . $address . "', '" . $number . "', '" . $email . "', '" . $details . "');";
You have NOW() at the end of the query that shouldn't be there.
Also note that your code has an SQL injection vulnerability (see mysql_real_escape_string()), I suggest you to prepare queries via PDO.
protect from possible SQL injection:
$name = mysql_real_escape_string($name);
$address = mysql_real_escape_string($address);
$number = mysql_real_escape_string($number);
$email = mysql_real_escape_string($email);
$details = mysql_real_escape_string($details);
replace with:
$query = "
INSERT INTO registrationdetails (`name`, `address`, `number`, `email`, `details`)
VALUES ('$name', '$address', '$number', '$email', '$details')");
$query = "
INSERT INTO registrationdetails (name, address, number, email, details, date_time)
VALUES ('{$name}', '{$address}', '{$number}', '{$email}', '{$details}', NOW())
";
Replace the date_time with your column_name. And remember to escape all submitted values with mysql_real_escape_string before inserting them into the database.

Categories