Insert Into with PDO - php

I new with PHP, MySQL and PDO.
With a lot of search, I made this piece of code to insert a new user/customer with a password.
<?php
require_once '../../src/mysql/dbconfig.php';
try
{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
}
catch (PDOException $pe)
{
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$stmt = $conn -> prepare($sql);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt -> bindValue(":email", $email);
$stmt -> bindValue(":password", $password);
$sql = "INSERT INTO customer (email, password) VALUES (:email, SHA2(:password,512))";
$stmt -> execute();
$conn = null;
?>
<html>
<body>
Welcome <?php echo $_POST["email"]; ?><br>
Your password is: <?php echo $_POST["password"]; ?>
</body>
</html>
When I submit, go to another PHP page, say the user's email and password.
So when I do SELECT * FROM, I receive an empty SET.
(Basically, the Insert is not working, but on the PHP page, it says the information that was inserted in the INSERT)
What am I doing wrong?

Basically, what I was doing wrong was calling a statement after its values.
<?php
require_once '../../src/mysql/dbconfig.php';
try
{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
}
catch (PDOException $pe)
{
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$sql = "INSERT INTO customer (email, password) VALUES (:email, SHA2(:password,512))";
$stmt = $conn -> prepare($sql);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt -> bindValue(":email", $email);
$stmt -> bindValue(":password", $password);
$stmt -> execute();
$conn = null;
?>

Related

can't connect to database with php (mysql) [duplicate]

If I want to put the connection in an external file, what part of this code should be in that external file?
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
This part will go in external file e.g connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
and then your code will look like
require("connection.php");
try {
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Till this part can go to external file, and can be used to open a connection where ever required.

No database selected - php and phpmyadmin

I am trying to connect my php code to my database and once I input and submit things like username, email address, and password in my html form. They will be sent to my database and shown in specific columns and there will be text like "New record has been created successfully" on my page. But for now, an error occurs instead.
The following is my php code
<?php
$visitorname = $emailaddress = $visitorpassword = $confirmpassword = "";
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$visitorname = input($_POST["visitorname"]);
$emailaddress = input($_POST["emailaddress"]);
$visitorpassword = input($_POST["visitorpassword"]);
$confirmpassword = input($_POST["confirmpassword"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
}
function input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($visitorpassword == $confirmpassword){
// Create connection
$conn = new mysqli($servername, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$id = mysqli_insert_id($conn);
$sql = "INSERT INTO registereduser (id, username, emailaddress,
hashedpassword) VALUES ($id, $visitorname, $emailaddress,
$hashed_password)";
if ($conn->query($sql) === TRUE){
echo "New record created successfully";
}else{
echo "Errors " . $sql . "<br>" . $conn->error;
}
$conn->close();
}else{
echo "Passwords do not match";
}
?>
The following is the error output shown on my web page:
Connected successfullyErrors INSERT INTO registereduser (id, username, emailaddress, hashedpassword) VALUES (0, Josh5577, josh1998#hotmail.com, $2y$10$RMasEdVOskmcXbmfchLeBeUzLa5l38jXFaCQN7vMEhR8A0mU/iiC6)
No database selected
Please use below code for connection
$conn = new mysqli($servername, $username, $password, $dbname);
You can try to change
// Create connection
$conn = new mysqli($servername, $dbname);
to
// Create connection
$conn = new mysqli($servername, $username, $password);
mysqli_select_db($conn, $dbname);

PDO. How to put the connection in an external file

If I want to put the connection in an external file, what part of this code should be in that external file?
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
This part will go in external file e.g connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
and then your code will look like
require("connection.php");
try {
$sql = "UPDATE bookmarks
SET podcast=122, text='some text'
WHERE id = 152";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Till this part can go to external file, and can be used to open a connection where ever required.

Using password_verify on existing password

I'm trying to check the password and username of someone before they log in to my website. The passwords are all stored in password_hash($password1, PASSWORD_BCRYPT); I'm not sure as to what I'm doing wrong. At the moment, No matter what I type in, It always says Incorrect.
<?php
require 'privstuff/dbinfo.php';
$username = $_POST["username"];
$password1 = $_POST["password1"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Connection Failed. Please send an email to owner#othertxt.com regarding this problem.";
exit();
}
if ($stmt = $mysqli->prepare("SELECT `username`, `password` FROM `accounts` WHERE username = ? AND password = ?")) {
$result = mysqli_query($mysqli,"SELECT `password` FROM `accounts` WHERE username = $username");
$stmt->bind_param("ss", $username, password_verify($password1, $result);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows) {
echo("Success");
}
else {
echo("Incorrect");
}
}
$mysqli->close();
?>
This is the register.php
<?php
require 'privstuff/dbinfo.php';
$firstname = $_POST["firstname"];
$password1 = $_POST["password1"];
$email = $_POST["email"];
$ip = $_SERVER['REMOTE_ADDR'];
$username = $_POST["username"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Connection Failed. Please send an email to owner#othertxt.com regarding this problem.";
exit();
}
if ($stmt = $mysqli->prepare("INSERT INTO `accounts`(`firstname`, `username`, `password`, `email`, `ip`) VALUES (?,?,?,?,?)")) {
$db_pw = password_hash($password1, PASSWORD_BCRYPT);
$stmt->bind_param("sssss", $firstname, $username, $db_pw, $email, $ip);
$stmt->execute();
if ($stmt->affected_rows > 0) {
echo "Account successfuly created";
}
$stmt->close();
}
$stmt->close();
$mysqli->close();
?>
I fixed the issue.. I was using password_verify incorrectly.
<?php
require 'privstuff/dbinfo.php';
$username = $_POST["username"];
$password1 = $_POST["password1"];
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT `password` FROM `accounts` WHERE username = ?")) {
/* Bind parameters: s - string, b - blob, i - int, etc */
$stmt -> bind_param("s", $username);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
/* Close statement */
$stmt -> close();
}
if(password_verify($password1, $result))
{
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
echo '<script type="text/javascript"> window.open("textbomber.php","_self");</script>';
}else{
echo '<script type="text/javascript"> alert("Incorrect Username/Password"); window.open("login.html","_self");</script>';
}
$mysqli->close();
?>
This problem should be solved differently. Only make a single query and get the password-hash by the given username. Then the check should be done in your code, not inside a second query:
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
This function will return true or false, depending on whether the password matched the stored password-hash. You cannot compare the password-hashes directly in the SQL query, because of the random salt added to each password.

Data not inserting into database

So I have my form that sends data to my php file that then enters it into the database. Here's the php backend part
<?php
$db = new mysqli('localhost','root','x','app');
$username = $_POST['username'];
$db->query("INSERT INTO people (first_name) VALUES ('{$username}'");
?>
But my question is, why isn't username being put into the database?
You are missing a bracket ) in the following line:
("INSERT INTO people (first_name) VALUES ('{$username}' ")
^ // <= right there
change it to:
("INSERT INTO people (first_name) VALUES ('{$username}')")
Yet, as pointed out in comments, you are open to SQL injection when using your present method.
Use prepared statements, or PDO.
Here follows an example of a prepared statement:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = #mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$mysqli) {
die('Connect Error: ' . mysqli_connect_error());
}
// $username = $_POST['username'];
$username = mysqli_real_escape_string($mysqli,$_POST['username']);
$sql = ("INSERT INTO people (first_name) VALUES (?)");
$stmt = $mysqli->prepare($sql) or die("Failed Execution");
$stmt->bind_param('s', $username);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
Plus, using error reporting is important before going live.
http://www.php.net/mysqli_error
Should you want to get into learning PDO,
Here are a few tutorials for you to look into:
PDO tutorial one
PDO tutorial two
PDO tutorial three
Here is a PDO example:
<?php
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try{
$db= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$email = $_POST['email'];
$username = $_POST['username'];
$result_set = $db->prepare("INSERT INTO `yourTable` (`email`, `username`)
VALUES (:email, :username)");
$result_set->bindParam(1, $email);
$result_set->bindParam(2, $username);
$result_set->execute(array(':email' => $email, ':username' => $username));
echo "Data successfully written.";
return $db;
}catch(PDOException $e){
echo $e;
return false;
}
?>
PDO error handling links:
http://www.php.net/manual/en/pdo.error-handling.php
http://www.php.net/manual/en/pdo.errorinfo.php

Categories