Data not save to the database - php

I want to save form data to database. I get a success message in the url. But the data get not saved to the database. mysqli_stmt_execute($stmt); seems to get not executed. Can anyone explain me the below code error?
if (isset($_POST['register-submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$type = $_POST['utype'];
$sql = "INSERT INTO `users`(`idroles`, `user_email`, `first_name`, `last_name`, `password`) VALUES((SELECT `idroles` FROM `roles` WHERE `name`= $type), ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location../View/login_register.php");
exit();
} else if (mysqli_stmt_prepare($stmt, $sql)) {
$hashpwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $firstname, $lastname, $email, $hashpwd);
mysqli_stmt_execute($stmt);
header("Location:../View/login_register.php?success");
exit();
}
}

You can check if mysqli_stmt_execute succeded by doing so:
if(mysqli_stmt_execute($stmt)) {
header("Location:../View/login_register.php?success");
exit();
} else {
echo mysqli_error($conn);
exit();
}

Related

Why PDO data adding into header instead of insert into db?

I'm not sure if my code is ok, it seems ok to me but when I input data, data not insert but adding at url like index.php?firstname=Kid&lastname=Max&username=OfficialKidMax.
<?php
if (isset($_POST['memadd'])) {
include('conn.php');
$thisusername = $post["username"];
$thisemail = $post["email"];
$sql = "SELECT * FROM members WHERE username = : thisusername OR `email` = : thisemail LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->execute(['thisusername' => $thisusername] OR ['thisemail' => $thisemail]);
$user = $result = $stmt->fetchAll();
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
if(empty($user)){
$query = "INSERT INTO members (`usermid`, `firstname`, `lastname`, `username`, `email`, `phone`, `usernid`, `address`, `address2`, `zipcode`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->execute(array($_POST['usermid'], $_POST['firstname'], $_POST['lastname'], $_POST['username'], $_POST['email'], $_POST['phone'], $_POST['usernid'], $_POST['address'], $_POST['address2'], $_POST['zipcode']));
}
}$_SESSION['success'] = 'Record Added';
header( 'Location: success.php' );
Update
I change my code a little bit.
Hi, thanks for your reply. I changed my code a little bit. It's work well now.
<?php
ini_set('display_errors', 1); ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if ($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['memadd']) &&
include('conn.php')) {
$sql = "SELECT * FROM `members` WHERE `usermid` =? OR `email` =?";
$stmt = $conn->prepare($sql);
$stmt->execute([$_POST['usermid'], $_POST['email']]);
$result = $stmt->fetchAll();
if ($result) { // if member exists
if ($result['email'] === [$_POST['email']]) {
array_push($errors, "User email already exists");
}
if ($result['usermid'] === [$_POST["usermid"]]) {
array_push($errors, "User ID already exists");
}
if(empty($result)){
// I run this query code at first to check if INSERT is ok and it's worked.
//But problem happen after if add.
$query = "INSERT INTO members (`usermid`, `firstname`, `lastname`, `username`, `email`, `phone`, `usernid`, `address`, `address2`, `zipcode`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->execute(array($_POST['usermid'], $_POST['firstname'], $_POST['lastname'], $_POST['username'], $_POST['email'], $_POST['phone'], $_POST['usernid'], $_POST['address'], $_POST['address2'], $_POST['zipcode']));
}
}
$_SESSION['message'] = 'Record Added';
header( 'Location: madd.php' );
I think this code is ok, or maybe not because I'm getting another problem.
if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) { ?>
<p><?php echo $error; ?></p>
<?php } ?>
</div>
<?php endif ?>
[21-Apr-2021 01:21:49 UTC] PHP Warning: count(): Parameter must be an array or an object that implements Countable in /errors.php on line 1
To save your self some grief learning php. These two links will help.
https://phptherightway.com/
Easy to read PDO tutorial.
https://phpdelusions.net/pdo
I did test this so there may still be some errors.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (isset($_POST['memadd'])) {
include('conn.php');
//
// Not sure what $post is. I assumen you ment $_POST
// Are these really needed?
// $thisusername = $post["username"];
// $thisemail = $post["email"];
// Removed the space after the :
// My optinion but if you habe to use the ` for anything. It's time to be more descriptive in your names.
//
$sql = "SELECT * FROM members WHERE username = :thisusername OR `email` = :thisemail LIMIT 1";
$stmt = $conn->prepare($sql);
//
// Not sure what the OR was doing.
//
$stmt->execute([
':thisusername' => $_POST['username'],
':thisemail' => $_POST['email']
]);
// Do you really need a second copy of the result?
$user = $result = $stmt->fetchAll();
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
if(empty($user)){
//
// I find usig the INSERT INTO table SET fld1=val1, fld2=val2, ...
// Much easyer to keep strack feilds and values.
//
$query = "INSERT INTO members (`usermid`, `firstname`, `lastname`, `username`, `email`, `phone`, `usernid`, `address`, `address2`, `zipcode`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->execute(array($_POST['usermid'], $_POST['firstname'], $_POST['lastname'], $_POST['username'], $_POST['email'], $_POST['phone'], $_POST['usernid'], $_POST['address'], $_POST['address2'], $_POST['zipcode']));
//
// You not doing any testing. How do you know it worked?
//
}
}
$_SESSION['success'] = 'Record Added';
header( 'Location: success.php' );

Take id from one table and insert in another same time

I want to insert in the security the same id from users:
<?php
if (isset($_POST['reg_user'])) {
require 'db.php';
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password_1'];
$passwordRepeat = $_POST['password_2'];
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$country = $_POST['country'];
$city = $_POST['city'];
$address = $_POST['address'];
$zipCode = $_POST['zipCode'];
if (empty($username) || empty($email) || empty($password) || empty($passwordRepeat) || empty($firstName) || empty($lastName) || empty($country) || empty($city) || empty($address) || empty($zipCode)) {
header("Location: ../sign_up.php?error=emptyfields&uid=" . $username . "&mail=" . $email);
exit();
} elseif (strlen($username) < 3) {
header("Location: ../sign_up.php?error=short_username=" . $username . "");
exit();
} elseif (strlen($username) > 17) {
header("Location: ../sign_up.php?error=long_username=" . $username . "");
exit();
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../sign_up.php?error=invalidmailuid");
exit();
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../sign_up.php?error=invalidmail&uid=" . $username);
exit();
} elseif (!preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../sign_up.php?error=invaliduid&mail=" . $email);
exit();
} elseif ($password !== $passwordRepeat) {
header("Location: ../sign_up.php?error=passwordcheck&uid=" . $username . "&mail=" . $email);
exit();
} else {
$sql = "SELECT username FROM users WHERE username=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../sign_up.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../sign_up.php?error=usertaken&mail=" . $email);
exit();
} else {
$sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../sign_up.php?error=sqlerror");
exit();
} else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
$sql = "INSERT INTO security (username, firstName, lastName, country, city, address, zipcode) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "sssssss", $username, $firstName, $lastName, $country, $city, $address, $zipCode);
mysqli_stmt_execute($stmt);
header("Location: ../sign_up.php?signup=succes");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
header("Location: ../sign_up.php");
exit();
}
Replace username from security with id from "users" table, but I don't know the id from this user because it executes at the same time, any solutions?
P.S: ID, auto increment primary key
I want to know that security data is from that user (id).
You can get the last inserted id in mysqli using
$conn->insert_id;
Right after executing the insertion of the item. ($conn being the instance of the msqli class)

Inserting values to different tables based on variables

$username = $_POST['uid'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
$date = $_POST['date2'];
$stream = $_POST['relationship'];
$sql1 = "INSERT INTO users (uidUsers, emailUsers, pwdUsers, relationship) VALUES (?, ?, ?, ?);";
$sql2 = "INSERT INTO Family1 (username, application_filed, relationship) VALUES (?, ?, ?);";
$sql3 = "INSERT INTO Family2 (username, application_filed, relationship) VALUES (?, ?, ?);";
mysqli_query($sql1, $conn);
mysqli_query($sql2, $conn);
mysqli_query($sql3, $conn);
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result))
($username==$_SESSION['uid'] and $stream =='nursing');
mysqli_stmt_execute($stmt);
}
if (!mysqli_stmt_prepare($stmt, $sql3)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result))
($username==$_SESSION['uid'] and $stream =='doctoral');
mysqli_stmt_execute($stmt);
}
if (!mysqli_stmt_prepare($stmt, $sql1)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
if (!mysqli_stmt_prepare($stmt, $sql1)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $username, $email, hashedPwd,$stream);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?signup=success");
exit();
/////////////New Code////////////////
$username = $_POST['uid'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
$date = $_POST['date2'];
$stream = $_POST['relationship'];
$sql1 = "INSERT INTO users (uidUsers, emailUsers, pwdUsers, relationship) VALUES (?, ?, ?, ?);";
$sql2 = "INSERT INTO Family1 (username, application_filed, relationship) VALUES (?, ?, ?);";
$sql3 = "INSERT INTO Family2 (username, application_filed, relationship) VALUES (?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
header("Location: ../signup.php?error=sqlerror");
exit();
} else if ($username==$_SESSION['uid'] && $stream =='nursing') {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
mysqli_stmt_execute($stmt);
}
if (!mysqli_stmt_prepare($stmt, $sql3)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else if ($username==$_SESSION['uid'] && $stream =='doctoral') {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
mysqli_stmt_execute($stmt);
}
if (!mysqli_stmt_prepare($stmt, $sql1)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $username, $email, $hashedPwd, $stream);
mysqli_stmt_execute($stmt);
header("Location: ../signup.php?signup=success");
exit();
}
I was wondering if someone could point me in the right direction. I have this code. They idea I had behind it is to insert values into different tables depending on variables being passed.
So when user fills out a form and selects $stream="nursing" I want results to go to table 'users' and 'Family1', but not 'Family2' table. and if user selects $stream='doctoral' results should go to table 'users' and 'Family2', and not go to 'Family1'
But with my query I get results go to both table and also users table. And there is no restriction to what users selects, variable $stream being passed no matter what it is.
Is this the wrong way to go here? Did I completely mess up the logic?
For one thing, the mysqli_query() calls at the top will try to run the queries and will fail, since it has no understanding of the ? placeholders and you have the $conn and $sqlX variables the wrong way around.
But aside from that, let me fix the indentation for you so you can see what's actually happening for one of your statements:
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
header("Location: ../signup.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result))
($username==$_SESSION['uid'] and $stream =='nursing');
mysqli_stmt_execute($stmt);
}
Do you see what's happening here?
$sql2 is an INSERT query. If you were able to prepare that statement you try to get the result before the query is even executed. If you manage to retrieve a row of data from that result (which you can't since an INSERT query does not return any records), you then do a check on $username and $stream that has no effect. The call to execute the prepared statement is executed regardless of whether or not you managed to get anything from $result.
All your statements have the same problems, so I'll only fix this one.
Here's what I changed:
The whole $result step seemed unnecessary, so I removed it.
I replaced and with && because of my personal preference. There was once a reason why it became my preference, but I forget. It's mostly for consistency between programming languages, since many languages use && and only a few use and.
Since there's no point in binding params to a statement you're not planning to execute, I moved that into the if-statement.
Since I now ended up with an else { if { ... } } construction, I simplified that down to an else if { ... } for cleaner code.
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql2)) {
header("Location: ../signup.php?error=sqlerror");
exit();
} else if ($username==$_SESSION['uid'] && $stream =='nursing') {
mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream);
mysqli_stmt_execute($stmt);
}
Now, the query $sql2 is only executed if the $username matches the current uid from the session and the user selected the nursing stream.

Is there a way to INSERT data from 2 DIFFERENT forms and INSERT into 1 row in column?

I have table of users which have following columns: user_id,username,first_name,last_name, email,token,password,location, phone.
I have 2 forms on two different pages. 1. registration.php 2. user_info.php.
In registration.php I'm getting user's email, username, and password. In user_info.php I'm getting user's first, lastname, country, phone.
I want to insert both form data in 1 row. so Is there any way?
right now with my code. it inserts info from both forms into database but it's inserting in each form data in 2 different rows.
here is my registration.php
<?php
if (isset($_POST['signup-submit'])) {
$url = "https://www.google.com/recaptcha/api/siteverify";
$data = ['secret' => "[xxxx]", 'response' => $_POST['token'], 'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = array('http' => array('header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data)));
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$res = json_decode($response, true);
if ($res['success'] == true) {
require("dbh.inc.php");
require("functions.php");
$username = escape($_POST['username']);
$email = escape($_POST['email']);
$token = bin2hex(random_bytes(50));
$password = escape($_POST['password']);
$passwordRepeat = escape($_POST['confirm_password']);
if (empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header("Location: ../registration.php?error=emptyfields");
exit();
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL) || !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../registration.php?error=invalidmailuid");
exit();
} elseif (strlen($username) <= '6') {
header("Location: ../registration.php?error=usernamecheck");
exit();
} elseif (strlen($password) <= '8') {
header("Location: ../registration.php?error=passwordcheck");
exit();
} elseif ($password !== $passwordRepeat) {
header("Location: ../registration.php?error=passwordverify");
exit();
} else {
$sql = "SELECT username, email FROM users WHERE username = ? AND email = ?";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../registration.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $username, $email);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../registration.php?error=usermailtaken");
exit();
} else {
$sql = "INSERT INTO users(username, email, password, token, joined) VALUES(?, ?, ?, ?, now())";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../registration.php?error=sqlerror2");
exit();
} else {
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $username, $email, $hashed_password, $token);
mysqli_stmt_execute($stmt);
header("Location: ../user_info.php");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($connection);
} else {
header("Location: ../registration.php?error=captcha");
exit();
}
} else {
header("Location: ../registration.php?error=emptyfields");
exit();
}
here is my user_info.php
<?php
if (isset($_POST['profile-submit'])) {
require("dbh.inc.php");
require("functions.php");
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$location = $_POST['location'];
$phone = $_POST['phone_number'];
if (empty($first_name) || empty($last_name) || empty($location) || empty($phone)) {
header("Location: ../user_info.php?error=emptyfields");
exit();
} else {
$sql = "INSERT INTO users(first_name, last_name, location, phone) VALUES(?, ?, ?, ?)";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../user_info.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "sssi", $first_name, $last_name, $location, $phone);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success");
exit();
}
}
mysqli_stmt_close($stmt);
mysqli_close($connection);
} else {
header("Location: ../user_info.php?error");
exit();
}
You need to use an UPDATE instead of an INSERT on user_info.php
INSERT adds new rows. https://dev.mysql.com/doc/refman/8.0/en/insert.html
INSERT inserts new rows into an existing table.
UPDATE modifies data in a row. https://dev.mysql.com/doc/refman/8.0/en/update.html
UPDATE is a DML statement that modifies rows in a table.
When you do an UPDATE you need to add a WHERE clause to update only the row you want. You usually do this with the primary key which I assume in this case is user_id.
You can use mysqli_insert_id($connection) to get the last id inserted after your INSERT query runs. I suggest then storing that in a $_SESSION variable and then accessing that on user_info.php rather than passing is via POST or GET. That way, another user can't just type in an ID in the GET or POST request and update another user's info. Here is some code to guide you.
registration.php
//start the session
session_start();
...
...
} else {
mysqli_stmt_bind_param($stmt, "sssi", $first_name, $last_name, $location, $phone);
mysqli_stmt_execute($stmt);
$_SESSION['user_id'] = mysqli_insert_id($connection);
header("Location: ../index.php?signup=success");
exit();
}
}
....
....
user_info.php
....
....
if (empty($first_name) || empty($last_name) || empty($location) || empty($phone) || !isset($_SESSION['user_id')) {
header("Location: ../user_info.php?error=emptyfields");
exit();
} else {
$sql = "UPDATE users SET first_name = ?, last_name = ?, location = ?, phone =? WHERE user_id = ?";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../user_info.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "sssi", $first_name, $last_name, $location, $phone, $_SESSION['user_id']);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success");
exit();
}
....
....
in registration.php you need to get the last inserted Id before going to user_info.php
mysqli_stmt_bind_param($stmt, "ssss", $username, $email, $hashed_password, $token);
mysqli_stmt_execute($stmt);
//get last inserted id
$last_id = mysqli_insert_id($connection);
header("Location: ../user_info.php?id='.$last_id.'");
exit();
in user_info.php use update in your query with where id = $_GET['id']
if (isset($_POST['profile-submit'])) {
require("dbh.inc.php");
require("functions.php");
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$location = $_POST['location'];
$phone = $_POST['phone_number'];
if (empty($first_name) || empty($last_name) || empty($location) || empty($phone)) {
header("Location: ../user_info.php?error=emptyfields");
exit();
} else {
$sql = "UPDATE users SET first_name = ?, last_name = ?, location = ?, phone =? WHERE id = ?";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../user_info.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "sssii", $first_name, $last_name, $location, $phone, $_GET['id']);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success");
exit();
}
}
mysqli_stmt_close($stmt);
mysqli_close($connection);
}else {
header("Location: ../user_info.php?error");
exit();}

Inserting into two different database tables

I have a form that will insert users input from a form into database, I want to store the email in a separate table to the users.
So I want the email in an accounts table and then the username and password in a users table. For anyone wondering why, the application I want to build will allow users to create a new user after dying but can have stuff stored in the accounts that will be carried over.
I tried working with multiple of the same code but just gets too much and get lost in it all. There must be an easier way to do than multiple copied of stretched code.
$sql = "SELECT user_name FROM users WHERE user_name=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=Sql_Error");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $character);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../register.php?error=CharacterTaken&email=".$emailAddress);
exit();
} else {
$sql = "INSERT INTO users (user_name, user_email, user_password) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=Sql_Error");
exit;
} else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $character, $emailAddress, $hashedPwd);
mysqli_stmt_execute($stmt);
header("Location: ../register.php?success=Account Created.");
If you wish to insert separate data in separate tables I suggest you just to use 2 separate INSERT queries.
As there is one part of your code doing it already, the easiest way is to adjust it and duplicate it:
Replace this part of code
$sql = "INSERT INTO users (user_name, user_email, user_password) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=Sql_Error");
exit;
} else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $character, $emailAddress, $hashedPwd);
mysqli_stmt_execute($stmt);
With this:
$sql = "INSERT INTO users (user_name, user_password) VALUES (?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=Sql_Error");
exit;
} else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ss", $character, $hashedPwd);
mysqli_stmt_execute($stmt);
$sql = "INSERT INTO accounts (user_email) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=Sql_Error");
exit;
} else {
mysqli_stmt_bind_param($stmt, "s", $emailAddress);
mysqli_stmt_execute($stmt);

Categories