inserting data into tables that share foreign keys - php

I have 2 tables that require insertion from a single form.
Table1 - user_info(user_id(primary), full_name, username, user_password, email)
Table 2 - user_personal_info(user_id(foreign), username(foreign), full_name(foreign), user_profession, user_phone, age)
The user_id is auto-increment.
I am trying to take the information received on the register form and insert them into each table. However, the first table takes all the information and the second one does not. I've tried doing two separate inserts with no success. Any help would be appreciated.
$full_name = $_POST['full_name'];
$username = $_POST['username'];
$email = $_POST['email'];
$user_password = $_POST['user_password'];
$password_hash = password_hash($user_password, PASSWORD_BCRYPT);
$id = $_SESSION['user_id'];
$user_profession = NULL;
$user_phone = NULL;
$age = NULL;
$query_user_info = $connection -> prepare("SELECT * FROM user_info WHERE EMAIL=:email");
$query_user_info->bindParam("email", $email, PDO::PARAM_STR);
$query_user_info->execute();
if ($query_user_info-> rowCount() > 0) {
echo '<p class="error">The email address is already registered!</p>';
}
if ($query_user_info-> rowCount() == 0) {
$query_user_info = $connection->prepare("INSERT INTO user_info(full_name,username,user_password,email) VALUES (:full_name, :username, :password_hash,:email)");
$query_user_info->bindParam("full_name", $full_name, PDO::PARAM_STR);
$query_user_info->bindParam("username", $username, PDO::PARAM_STR);
$query_user_info->bindParam("password_hash", $password_hash, PDO::PARAM_STR);
$query_user_info->bindParam("email", $email, PDO::PARAM_STR);
$result = $query_user_info->execute();
$query_user_personal_info = $connection->prepare ("INSERT INTO user_personal_info(user_id,full_name, username, email, user_profession, user_phone, age) VALUES (:id, :full_name, :username, :email, :user_profession, :user_phone, :age)");
$query_user_personal_info->bindParam("user_id", $id, PDO::PARAM_INT);
$query_user_personal_info->bindParam("full_name", $full_name, PDO::PARAM_STR);
$query_user_personal_info->bindParam("username", $username, PDO::PARAM_STR);
$query_user_personal_info->bindParam("email", $email, PDO::PARAM_STR);
$query_user_personal_info->bindParam("user_profession", $user_profession, PDO::PARAM_STR);
$query_user_personal_info->bindParam("user_phone", $user_phone, PDO::PARAM_INT);
$query_user_personal_info->bindParam("age", $age, PDO::PARAM_INT);
$result2 = $query_user_personal_info->execute();
if ($result) { // create a profile page.
echo '<p class="success">Your registration was successful!</p>';
} else {
echo '<p class="error">Something went wrong!</p>';
}
if ($result2) { // create a profile page.
echo '<p class="success">Your registration was successful!</p>';
} else {
echo '<p class="error">no bueno :(</p>';
}
}

Shouldn't you be getting the inserted ID from the user_info table?
Try this
$full_name = $_POST['full_name'];
$username = $_POST['username'];
$email = $_POST['email'];
$user_password = $_POST['user_password'];
$password_hash = password_hash($user_password, PASSWORD_BCRYPT);
$user_profession = NULL;
$user_phone = NULL;
$age = NULL;
$query_user_info = $connection -> prepare("SELECT * FROM user_info WHERE EMAIL=:email");
$query_user_info->bindParam("email", $email, PDO::PARAM_STR);
$query_user_info->execute();
if ($query_user_info-> rowCount() > 0) {
echo '<p class="error">The email address is already registered!</p>';
}
if ($query_user_info-> rowCount() == 0) {
$query_user_info = $connection->prepare("INSERT INTO user_info(full_name,username,user_password,email) VALUES (:full_name, :username, :password_hash,:email)");
$query_user_info->bindParam("full_name", $full_name, PDO::PARAM_STR);
$query_user_info->bindParam("username", $username, PDO::PARAM_STR);
$query_user_info->bindParam("password_hash", $password_hash, PDO::PARAM_STR);
$query_user_info->bindParam("email", $email, PDO::PARAM_STR);
$result = $query_user_info->execute();
$id = $query_user_info->lastInsertId();
$query_user_personal_info = $connection->prepare ("INSERT INTO user_personal_info(user_id,full_name, username, email, user_profession, user_phone, age) VALUES (:id, :full_name, :username, :email, :user_profession, :user_phone, :age)");
$query_user_personal_info->bindParam("user_id", $id, PDO::PARAM_INT);
$query_user_personal_info->bindParam("full_name", $full_name, PDO::PARAM_STR);
$query_user_personal_info->bindParam("username", $username, PDO::PARAM_STR);
$query_user_personal_info->bindParam("email", $email, PDO::PARAM_STR);
$query_user_personal_info->bindParam("user_profession", $user_profession, PDO::PARAM_STR);
$query_user_personal_info->bindParam("user_phone", $user_phone, PDO::PARAM_INT);
$query_user_personal_info->bindParam("age", $age, PDO::PARAM_INT);
$result2 = $query_user_personal_info->execute();
if ($result) { // create a profile page.
echo '<p class="success">Your registration was successful!</p>';
} else {
echo '<p class="error">Something went wrong!</p>';
}
if ($result2) { // create a profile page.
echo '<p class="success">Your registration was successful!</p>';
} else {
echo '<p class="error">no bueno :(</p>';
}
}
Also, are $user_profession, $user_phone, and $age required in your database? If not, then you don't need those values to insert into your table if they just default to null values.
Try changing it to this
$full_name = $_POST['full_name'];
$username = $_POST['username'];
$email = $_POST['email'];
$user_password = $_POST['user_password'];
$password_hash = password_hash($user_password, PASSWORD_BCRYPT);
$query_user_info = $connection -> prepare("SELECT * FROM user_info WHERE EMAIL=:email");
$query_user_info->bindParam("email", $email, PDO::PARAM_STR);
$query_user_info->execute();
if ($query_user_info-> rowCount() > 0) {
echo '<p class="error">The email address is already registered!</p>';
}
if ($query_user_info-> rowCount() == 0) {
$query_user_info = $connection->prepare("INSERT INTO user_info(full_name,username,user_password,email) VALUES (:full_name, :username, :password_hash,:email)");
$query_user_info->bindParam("full_name", $full_name, PDO::PARAM_STR);
$query_user_info->bindParam("username", $username, PDO::PARAM_STR);
$query_user_info->bindParam("password_hash", $password_hash, PDO::PARAM_STR);
$query_user_info->bindParam("email", $email, PDO::PARAM_STR);
$result = $query_user_info->execute();
$id = $query_user_info->lastInsertId();
$query_user_personal_info = $connection->prepare ("INSERT INTO user_personal_info(user_id,full_name, username, email) VALUES (:id, :full_name, :username, :email)");
$query_user_personal_info->bindParam("user_id", $id, PDO::PARAM_INT);
$query_user_personal_info->bindParam("full_name", $full_name, PDO::PARAM_STR);
$query_user_personal_info->bindParam("username", $username, PDO::PARAM_STR);
$query_user_personal_info->bindParam("email", $email, PDO::PARAM_STR);
$result2 = $query_user_personal_info->execute();
if ($result) { // create a profile page.
echo '<p class="success">Your registration was successful!</p>';
} else {
echo '<p class="error">Something went wrong!</p>';
}
if ($result2) { // create a profile page.
echo '<p class="success">Your registration was successful!</p>';
} else {
echo '<p class="error">no bueno :(</p>';
}
}

Related

How can I check if a user exists with PDO?

My PDO query is not working for some reason, the page itself doesn't seem to have any error, I've been trying to fix this for like 2 months and nothing worked, I got this "final" code which not seems to have any errors and it's still not working.
<?php
require 'database.php';
$message = '';
if (!empty($_POST['username']) && !empty($_POST['email']) && !empty($_POST['phone']) && !empty($_POST['password'])) {
$sql = "INSERT INTO users (username, email, phone, password) VALUES (:username, :email, :phone, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':phone', $_POST['phone']);
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(':password', $password);
$query = $con->prepare("SELECT username FROM users WHERE username = :username");
$query->bindParam(':username', $_POST['username']);
$query->execute();
if($query->rowCount() > 0){
?> Este usuario ya existe <?php
}
else {
if($stmt->execute()) {
header('Location: login.php');
}
else {
echo "OcurriĆ³ un error";
}
}
}
?>
I suppose that it's because you have used a inapropriate variable.
in initialisation of $stmt you used $conn and in $query you used $con
make sure to the rigth varaible

PDO insert not working correctly

When I login it's suppose to insert, but instead does nothing.. On my register php it inserts data to accounts, but when i insert data into online it won't work..
PS- I'm new to PDO so I don't know what i'm doing wrong
<?php
session_start();
if(isset($_SESSION['users']) != ""){
echo '<script type="text/javascript">','index();','</script>';
}
include('../php/dbConnect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query = 'SELECT * FROM `accounts` WHERE username = ?';
$queryprepare = $conn->prepare($query);
$queryprepare->bindParam(1, $username, PDO::PARAM_STR);
$queryprepare->execute();
$row = $queryprepare->fetch();
if($row['password'] == md5($password))
{
$_SESSION['online'] = true;
$_SESSION['users'] = $username;
$_SESSION['userid'] = $row['id'];
$_SESSION['name'] = $row['name'];
$_SESSION['age'] = $row['age'];
$_SESSION['image'] = $row['image'];
$check_row = 'SELECT * FROM `online` WHERE username = ?';
$check_row_fetch = $conn->prepare($check_row);
$check_row_fetch->bindParam(1, $username, PDO::PARAM_STR);
$check_row_fetch->execute();
$number_of_rows = $check_row_fetch->rowCount();
if($number_of_rows != 0) {
echo '<script type="text/javascript">','redirect();','</script>';
}
else{
$online_insert = 'INSERT INTO online (username, name, age, image) VALUES (?, ?, ?, ?)';
$online_insert_fetch = $conn->prepare($online_insert);
$online_insert_fetch->bindParam(1, $SESSION['users'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(2, $SESSION['name'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(3, $SESSION['age'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(4, $SESSION['image'], PDO::PARAM_STR);
$online_insert_fetch->execute();
echo '<script type="text/javascript">','redirect();','</script>';
}
}
else{
echo("Wrong Credentials");
}
?>

Prepared Statements Checking if row exists

I am new to Prepared Statements in Php and and wondering how you would best approach checking if a row already exists as I seem to be getting confused at this stage:
<?php
include '../config.php';
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
if(mysqli_num_rows($stmt) > 0) {
$email = $_POST['email'];
$password = $_POST['password'];
$stmt->execute();
header('Location: ../login.php');
} else {
echo 'user already exists';
}
$stmt->close();
$conn->close();
?>
The above returns the else statement, if I switch them around it will insert again making use of the else statement and inserting the record but still not checking.
** UPDATE **
Here is my updated code for you to see after assistance below..
<?php
include '../config.php';
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =?");
$stmt_check->bind_param("s", $email);
$stmt_check->execute();
if($stmt_check->num_rows > 0) {
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
// header('Location: ../login.php');
}
$stmt->close();
$conn->close();
?>
mysqli_num_rows applicable to SELECT statement.
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
if(mysqli_num_rows($stmt_check) > 0)
Updated Code
<?php
include '../config.php';
$email = $_POST['email'];
$password = $_POST['password'];
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
if($stmt_check->num_rows > 0){
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
header('Location: ../login.php');
}
$stmt->close();
$conn->close();
?>
Quick Link
mysqli_num_rows
mysql_num_rows
Which States,
This command is only valid for statements like SELECT or SHOW that
return an actual result set. To retrieve the number of rows affected
by a INSERT, UPDATE, REPLACE or DELETE query, use
mysql_affected_rows().
Edit 1
Change
if(mysqli_num_rows($stmt_check) > 0){
To
if($stmt_check->num_rows > 0){
See Example2 of PHP mysqli_num_rows() Function
This is my updated code, please try
<?php
include '../config.php';
$email = $_POST['email'];
$password = $_POST['password'];
$stmt_check = $conn->prepare("SELECT * FROM users WHERE email =? AND password =?");
$stmt_check->bind_param("ss", $email, $password);
$stmt_check->execute();
$stmt_check->store_result();
$numberofrows = $stmt_check->num_rows;
if(($numberofrows) > 0)
echo 'user already exists';
} else {
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $email, $password);
$stmt->execute();
header('Location: ../login.php');
}
$stmt->close();
$conn->close();
?>
Take a look at mysqli_stmt_affected_rows()
<?php include '../config.php';
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $_POST['email'], $_POST['password']);
$stmt->execute();
if(mysqli_stmt_affected_rows($stmt) > 0)
{
header('Location: ../login.php');
}
else
{
echo 'user already exists';
}
$stmt->close();
$conn->close();
?>
<?php include '../config.php';
$stmt = $conn->prepare("INSERT INTO users (email, password) VALUES (?, ?)");
$stmt->bind_param("ss", $_POST['email'], $_POST['password']);
$result = $stmt->execute(); // this return a bool: true if row affected otherwise false
if($result)
{
header('Location: ../login.php');
}
else
{
echo 'user already exists';
}
$stmt->close();
$conn->close();
?>

Seeing whether the email used is in the database - PHP

I'm attempting to access my database to see if the email has been
used previously. All my attempts have failed. I can get the form to
enter the information into the database but that is it. I'm very new
to PHP so any help is appreciated.
<?php
require 'database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$sql = "INSERT INTO noodles_gamification (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ){;
$message = 'Successfully created new user';
}else {
$stmt = $conn->prepare('SELECT email FROM noodles_gamification WHERE email = :email');
$stmt->execute(array(':email' => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'email provided is already in use.';
}
}
endif;
?>
I think you need to check if email is already exist or not before inserting new record to database Just modify your if condition some think like
<?php
require 'database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$stmt = $conn->prepare('SELECT email FROM noodles_gamification WHERE email = :email');
$stmt->execute(array(':email' => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'email provided is already in use.';
} else {
$sql = "INSERT INTO noodles_gamification (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ){;
$message = 'Successfully created new user';
}
}
else {
}
endif;
?>

Check if the email exists using pdo

This is the section I use to add users.
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: ./index.php");
}
require 'conn.php';
$message = '';
if(!empty($_POST['name']) &&!empty($_POST['email']) && !empty($_POST['password'])):
// Enter the new user in the database
$sql = "INSERT INTO users (name, email, password) VALUES (:name,:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
I personally do it by using a query and an if statement
$query = $conn->prepare("SELECT * FROM users WHERE email = :email");
$query->bindParam(':email', $_POST['email']);
if ($query->rowcount() = 0)
{
// insert account into database
}
else {
// display error message
}
To check if the email exists or not, you have to write a query whether that email is stored in the database. If the query result is not empty, you can show a message that the email exists. If the query result is empty, you can make him a new user.
For that you have to write this query
$sql="select name from user where email='$email'";
$stmt = $conn->prepare($sql);
if ($stmt->rowcount() = 0)
{
$sql = "INSERT INTO users (name, email, password) VALUES (:name,:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':name', $_POST['name']);
$stmt->bindValue(':email', $_POST['email']);
$stmt->bindValue(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
}
else {
$msg="Email already exists";
}

Categories