I am trying to register customers for a continuing education web site I am creating and need to add multiple entries to the phpMyAdmin table "users" for registration purposes. I am trying to add multiple entries, 25 total.
As you will see, I have tried the mysqli_multi_query() function to add them all but I cannot create a new record of those entries.
It shows that I am connected to the database and I have checked all values in the code with those in the table and they are ordered. So my questions are:
Is there a limit of entries per table?
Is it best to add few entries at a time than a sign-in page with multiple lines?
Am I trying to do too much in one file and need to split my job?
Error I am getting:
You are connected to the database. Error: INSERT INTO users (myName, home1, home2) VALUES (?, ?, ?);INSERT INTO users (city, ste, zip) VALUES (?, ?, ?);INSERT INTO users (email, certification, experience) VALUES (?, ?, ?);INSERT INTO users (employer, marketing, gender) VALUES (?, ?, ?);INSERT INTO users (dob, recert, full_name) VALUES (?, ?, ?);INSERT INTO users (phone, bHome1, bHome2) VALUES (?, ?, ?);INSERT INTO users (bCity, bState, bZip) VALUES (?, ?, ?);INSERT INTO users (payment, cardNum, expDate) VALUES (?, ?, ?);INSERT INTO users (pwd) VALUES (?);
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 '?, ?, ?);INSERT INTO users (city, ste, zip) VALUES (?, ?, ?);INSERT INTO users (' at line 1
The code so far validates all entries, checks if there are blank entries, and uses the function test-input. Any help is appreciated, including sources from where to learn PHP that worked better for your education. Thanks in advance and thank you for listening.
<?php
// Defined variables for validation
$myNameErr = $home1Err = $home2Err =$cityErr = $steErr = $zipErr = $emailErr = "";
$certificationErr = $experienceErr = $employerErr = $marketingErr = "";
$genderErr = $dobErr = $recertErr = $full_nameErr = $phoneErr = $bHome1Err = "";
$bHome2Err = $bCityErr = $bStateErr = $bZipErr = $paymentErr = $cardNumErr = "";
$expDateErr = $pwdErr = $pwd2Err = "";
$myName = $home1 = $home2 = $city = $ste = $zip = $email = "";
$certification = $experience = $employer = $marketing = "";
$gender = $dob = $recert = $full_name = $phone = $bHome1 = "";
$bHome2 = $bCity = $bState = $bZip = $payment = $cardNum = "";
$expDate = $pwd = $pwd2 = "";
// Validating fields by checking if fields are empty
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Checks full name
if (empty($_POST['myName'])) {
$myNameErr = "Name required.";
} else {
$myName = test_input($_POST['myName']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' -.]*$/", $myName)) {
$myNameErr = "Only letters and white space allowed";
}
}
// Checks address
if (empty($_POST['home1'])) {
$home1Err = "Address required.";
} else {
$home1 = test_input($_POST['home1']);
}
// Checks additional address input
if (empty($_POST['home2'])) {
$home2 = test_input($_POST['home2']);
}
// Checks for city
if (empty($_POST['city'])) {
$cityErr = "City is required.";
} else {
$city = test_input($_POST['city']);
}
// Checks for state
if (empty($_POST['ste'])) {
$steErr = "State is required.";
} else {
$ste = test_input($_POST['ste']);
}
// Checks for zipcode
if (empty($_POST['zip'])) {
$zipErr = "Zip code is required.";
} else {
$zip = test_input($_POST['zip']);
}
// Checks for email and if format is correct
if (empty($_POST['email'])) {
$emailErr = "Email is required.";
} else {
$email = test_input($_POST['email']);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
// Confirms the current email
if (empty($_POST['email2'])) {
$email2Err = "Confirm your email.";
} else {
$email2 = test_input($_POST['email2']);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email2Err = "Invalid email format";
}
// Check if emails match
if ($email != $email2) {
$email2Err = "Emails don't match!";
}
}
// Checks for modality certification
if (empty($_POST['certification'])) {
$certificationErr = "Current certification is required.";
} else {
$certification = test_input($_POST['certification']);
}
// Checks for years of experience
if (empty($_POST['experience'])) {
$experienceErr = "Years of experience are required.";
} else {
$experience = test_input($_POST['experience']);
}
// Checks for the current employer
if (empty($_POST['employer'])) {
$employerErr = "Current employer required.";
} else {
$employer = test_input($_POST['employer']);
}
// Input about how they heard about us
if (empty($_POST['marketing'])) {
$marketing = "";
} else {
$marketing = test_input($_POST['marketing']);
}
// Checks for gender
if (empty($_POST['gender'])) {
$genderErr = "Gender required.";
} else {
$gender = test_input($_POST['gender']);
}
// Check the date of birth
if (empty($_POST['dob'])) {
$dobErr = "Date of birth required.";
} else {
$dob = test_input($_POST['dob']);
}
// Checks their end of certification date
if (empty($_POST['recert'])) {
$recertErr = "Recertification date required.";
} else {
$recert = test_input($_POST['recert']);
}
// Checks name as in credit card
if (empty($_POST['full_name'])) {
$full_nameErr = "Name as written in credit card required.";
} else {
$full_name = test_input($_POST['full_name']);
}
// Checks for phone number
if (empty($_POST['phone'])) {
$phoneErr = "Phone number is required.";
} else {
$phone = test_input($_POST['phone']);
}
// Billing Information
// Checks for billing address
if (empty($_POST['bHome1'])) {
$bHome1 = "";
} else {
$bHome1 = test_input($_POST['bHome1']);
}
// Checks for billing address 2
if (empty($_POST['bHome2'])) {
$bHome2 = "";
} else {
$bHome2 = test_input($_POST['bHome2']);
}
// Checks for billing city
if (empty($_POST['bCity'])) {
$bCity = "";
} else {
$bCity = test_input($_POST['bCity']);
}
// Checks for billing state
if (empty($_POST['bState'])) {
$bState = "";
} else {
$bState = test_input($_POST['bState']);
}
// Checks for billing zip code
if (empty($_POST['bZip'])) {
$bZip = "";
} else {
$bZip = test_input($_POST['bZip']);
}
// Checks for payment mode
if (empty($_POST['payment'])) {
$paymentErr = "Mode of payment is required.";
} else {
$payment = test_input($_POST['payment']);
}
// Checks for credit card number
if (empty($_POST['cardNum'])) {
$cardNumErr = "Credit card number required.";
} else {
$cardNum = test_input($_POST['cardNum']);
}
// Checks for expiration date
if (empty($_POST['expDate'])) {
$expDateErr = "Card's expiration date required.";
} else {
$expDate = test_input($_POST['expDate']);
}
// Checks for password
if (empty($_POST['pwd'])) {
$pwdErr = "Password required.";
} else {
$pwd = test_input($_POST['pwd']);
}
// Asks to confirm password and if both match
if (empty($_POST['pwd2'])) {
$pwd2Err = "Confirm your email.";
} else {
$pwd2 = test_input($_POST['pwd2']);
// Check if passwords match
if ($pwd != $pwd2) {
$pwd2Err = "Passwords don't match!";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST['submit'])){
$myName = $_POST['myName'];
$home1 = $_POST['home1'];
$home2 = $_POST['home2'];
$city = $_POST['city'];
$ste = $_POST['ste'];
$zip = $_POST['zip'];
$email = $_POST['email'];
$certification = $_POST['certification'];
$experience = $_POST['experience'];
$employer = $_POST['employer'];
$marketing = $_POST['marketing'];
$gender = $_POST['gender'];
$dob = $_POST['dob'];
$recert = $_POST['recert'];
$full_name = $_POST['full_name'];
$phone = $_POST['phone'];
$bHome1 = $_POST['bHome1'];
$bHome2 = $_POST['bHome2'];
$bCity = $_POST['bCity'];
$bState = $_POST['bState'];
$bZip = $_POST['bZip'];
$payment = $_POST['payment'];
$cardNum = $_POST['cardNum'];
$expDate = $_POST['expDate'];
$pwd = $_POST['pwd'];
// Adding multiple values to database table users
$sql = "INSERT INTO TABLE users (myName, home1, home2) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (city, ste, zip) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (email, certification, experience) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (employer, marketing, gender) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (dob, recert, full_name) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (phone, bHome1, bHome2) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (bCity, bState, bZip) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (payment, cardNum, expDate) VALUES (?, ?, ?);";
$sql .= "INSERT INTO TABLE users (pwd) VALUES (?);";
// Trying to save to the database
if (mysqli_multi_query($con, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
$hashPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt->bind_param("sssssssssssssssssssssssss", $myName, $home1, $home2, $city, $ste, $zip,
$email, $certification, $experience, $employer, $marketing, $gender, $dob, $recert,
$full_name, $phone, $bHome1, $bHome2, $bCity, $bState, $bZip, $payment, $cardNum,
$expDate, $hashPwd);
mysqli_close($con);
}
Your multi-query is completely wrong. It will create nine new rows, each with a portion of the data for a user, instead of one. You only have one set of data, so you don't need multi_query at all.
You need
// Adding multiple values to database table users
$sql = "INSERT INTO TABLE users (myName, home1, home2, city, ste, zip, email, employer, marketing, gender, certification, experience, dob, recert, full_name, phone, bHome1, bHome2, bCity, bState, bZip, payment, cardNum, expDate, pwd) VALUES (?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
$stmt = $con->prepare($sql);
$hashPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt->bind_param("sssssssssssssssssssssssss", $myName, $home1, $home2, $city, $ste, $zip,
$email, $certification, $experience, $employer, $marketing, $gender, $dob, $recert,
$full_name, $phone, $bHome1, $bHome2, $bCity, $bState, $bZip, $payment, $cardNum,
$expDate, $hashPwd);
$result = $stmt->execute();
Tangentially Perpendicular & Rager pointed me in the right direction in the sense that my entries were wrong. Using multi-query (mysqli_multi_query) is the wrong way to do what I needed to do and had nothing to do with adding multiple entries into a table. mysqli_multi_query executes one or multiple queries which are concatenated by a semicolon (https://www.php.net/manual/en/mysqli.multi-query.php).
Yes, you can add as many entries per record as you want (if you want to complicate your life) but simple is better. Finally, the reason I could not get data into the table (besides using multi-query and that my entries were wrong), is that my version of MAMP (in a mac) was running version 7.4 and not PHP 8.0 as in my computer. Once I checked marked version 8 on MAMPs I was able to get my query in the table without any other issues.
You need to prepare your sql, bind the params and then execute. Forget the mysqli functions.
$sql = "INSERT INTO TABLE users (myName, home1, home2, city, ste, zip, email, employer, marketing, gender, certification, experience, dob, recert, full_name, phone, bHome1, bHome2, bCity, bState, bZip, payment, cardNum, expDate, pwd) VALUES (?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
$stmt = $con->prepare($sql);
$hashPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt->bind_param("sssssssssssssssssssssssss", $myName, $home1, $home2, $city, $ste, $zip,
$email, $certification, $experience, $employer, $marketing, $gender, $dob, $recert,
$full_name, $phone, $bHome1, $bHome2, $bCity, $bState, $bZip, $payment, $cardNum,
$expDate, $hashPwd);
$stmt->execute();
mysqli_close($con);
You're getting that error because mysql doesn't know what ? is. You are litterally try to execute INSERT INTO users (city, ste, zip) VALUES (?, ?, ?); which is not valid sql. The variables have to be converted first.
Also, this might be a little advanced for you but you can definitely refactor a lot of redundant code out of this... Just practice and you'll get it!
Here's a rough in of what I'm talking about
if ($_SERVER["REQUEST_METHOD"] != "POST") {
//Better to exit on smaller if then wrap everything in if statement.
die();
}
$list = [
'myName' => [ 'type' => 's', 'value' => '', 'err' => 'Name required.'],
'home1' => [ 'type' => 's', 'value' => '', 'err' => 'Address required.'],
'home2' => [ 'type' => 's', 'value' => '', 'err' => '']
// Complete all your entries
];
$hasErr = false;
foreach($list as $key => &$item){
if (empty($_POST[$key])) {
$item['value'] = $item['err'];
} else {
$hasErr = true;
$item['value'] = test_input($_POST[$key]);
switch($key){
case'myName':
if (!preg_match("/^[a-zA-Z-' -.]*$/", $item['value'])) {
$item['value'] = "Only letters and white space allowed";
}
break;
// Add more casses for more special proccessing.
}
}
}
unset($item); //Always unset pointers after loop.
if(!$hasErr){
$sql = "INSERT INTO users(";
$sqlCols = [];
$sqlVals = [];
foreach($list as $key => $item){
$sqlCols[] = $key;
$sqlVals[] = "?";
}
$sql .= implode(",", $sqlCols) . ") values ( " . implode(",", $sqlVals ). " )";
$stmt->prepare($sql);
foreach($list as $key => $item){
// Actually not sure this is possible, worth a shot though.
$stmt->pind_param($item['type'], $item['value']);
}
$stm->execute();
} else{
//Handle error
}
I am trying to POST select values from my HTML form into my Database with phpmysqli.
Somehow the value "-" results as an empty string. The other values are perfectly fine.
So echo $title with value "-" = "" ; with value "Dr." = "Dr."
My HTML:
<select
name="title"
class="form-control"
style="width: 50%;"
required
>
<option value="" disabled selected>Titula</option>
<option value="-">-</option>
<option value="Dr.">Dr.</option>
<option value="Prof. Dr.">Prof. Dr.</option>
</select>
My PHP:
<?php
$username = $_POST['username'];
$password = PASSWORD_HASH($_POST["password"], PASSWORD_DEFAULT);
$title = $_POST['title'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$birth = $_POST['birth'];
$street = $_POST['street'];
$city = $_POST['city'];
$country = $_POST['country'];
$zip = $_POST['zip'];
$father = $_POST['father'];
$mother = $_POST['mother'];
if (!empty($username) || !empty($password) || !empty($birth) || !empty($title) || !empty($mail) || !empty($phone) || !empty($fname) || !empty($lname) || !empty($street) || !empty($city) || !empty($country) || !empty($zip) || !empty($father) || !empty($mother)) {
$host = "localhost";
$dbUsername = "";
$dbPassword = "";
$dbname = "";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
mysqli_set_charset($conn,'utf8mb4');
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$SELECT = "SELECT mail From users Where mail = ? Limit 1";
$INSERT = "INSERT Into users (username, password, birth, title, mail, phone, fname, lname, street, city, country, zip, father, mother) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $mail);
$stmt->execute();
$stmt->bind_result($mail);
$stmt->store_result();
$rnum = $stmt->num_rows;
if ($rnum==0) {
$stmt->close();
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("ssssssssssssss", $username, $password, $birth, $title, $mail, $phone, $fname, $lname, $street, $city, $country, $zip, $father, $mother);
$stmt->execute();
echo "New record inserted sucessfully";
echo $title; //empty string
//header('Location: login.html');
} else {
echo "Someone already register using this email";
}
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
?>
I am assuming by "Boolean" that it is coming out as "false"...
Can anyone explain what could be wrong here?
My code may be flawed altogether, but I would like some constructive criticism.
<?php
if ($_SERVER['REQUEST_METHOD'] = "POST") {
include("mytableconn.php");
$firstName = mysqli_real_escape_string($conn, trim($_POST['firstn']));
$lastName = mysqli_real_escape_string($conn, trim($_POST['lastn']));
$email = mysqli_real_escape_string($conn, trim($_POST['uemail']));
$password = mysqli_real_escape_string($conn, trim($_POST ['userpasscode']));
$cryption = "$2y$10$";
$chars = "thisisseriouslyfucked1";
$crypchar = $cryption . $chars;
$crypass = crypt($password, $crypchar);
$user = $conn->prepare("
INSERT INTO mytable(first_name, last_name, e_mail, pass_word)
VALUES(?, ?, ?, ?)
");
$user = $user->bind_param("ssss", $firstName, $lastName, $email, $crypass);
$user->execute();
$user->close();
$conn->close();
}else {
echo("Sorry, an unexpected error occurred");
}
?>
When you prepare the sql you assign it as a variable - you should then test that variable before proceeding to check that the sql is valid.
mysqli_prepare() returns a statement object or FALSE if an error
occurred
<?php
if ( $_SERVER['REQUEST_METHOD'] = "POST" ) {
include("mytableconn.php");
$firstName = mysqli_real_escape_string($conn, trim($_POST['firstn']));
$lastName = mysqli_real_escape_string($conn, trim($_POST['lastn']));
$email = mysqli_real_escape_string($conn, trim($_POST['uemail']));
$password = mysqli_real_escape_string($conn, trim($_POST['userpasscode']));
$cryption = "$2y$10$";
$chars = "thisisseriouslyfucked1";
$crypchar = $cryption . $chars;
$crypass = crypt( $password, $crypchar );
$stmt = $conn->prepare("insert into `mytable` ( `first_name`, `last_name`, `e_mail`, `pass_word` ) values (?, ?, ?, ?)");
if( $stmt ){
$stmt->bind_param("ssss", $firstName, $lastName, $email, $crypass);
$stmt->execute();
$stmt->close();
}
$conn->close();
}else {
echo("Sorry, an unexpected error occurred");
}
?>
The script is already working fine but I want to insert a command that allows only if the username is not yet used.
if (isset($_POST['submit'])) {
$firstname = htmlentities($_POST['firstname'], ENT_QUOTES);
$lastname = htmlentities($_POST['lastname'], ENT_QUOTES);
$position = htmlentities($_POST['position'], ENT_QUOTES);
$username = htmlentities($_POST['username'], ENT_QUOTES);
$password = htmlentities($_POST['password_two'], ENT_QUOTES);
$uniqid = uniqid('', true);
if ( $firstname == '' || $lastname == '' || $position == '' || $username == '' || $password == '') {
$error = 'ERROR: Please fill in all required fields!';
renderForm($error, $firstname, $lastname, $position, $username, $password);
} else {
if ($stmt = $connection->prepare("INSERT INTO employee (uniqid, firstname, lastname, position, username, password) VALUES (?, ?, ?, ?, ?, ?)")) {
$stmt->bind_param("ssssss", $uniqid, $firstname, $lastname, $position, $username, $password);
$stmt->execute();
$stmt->close();
} else {
echo "ERROR: Could not prepare SQL statement.";
}
header("Location: regemployee.php");
}
} else {
renderForm();
}
Make username unique on the DB, then when you try to insert the same username in to the DB again, the insert will through an error.
Alternatively you could do a SELECT * FROM employee WHERE username = ? and check if results is > 0.
Then you would know it exists already.
Do another SELECT query which checks if the submitted username already exist:
$stmt = $connection->prepare("SELECT * FROM employee WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
Then get the number of results:
$stmt->store_result();
$noofres = $stmt->num_rows;
$stmt->close();
Then, create a condition that if it yet doesn't exist, it will do the insert query:
if($noofres == 0){
/* INSERT QUERY HERE */
} else {
echo 'Username already taken.';
}
I'm a beginner here and i am learning the basic in converting from MySQL to MySQLi. I am currently working on this registration page which I would want to convert to the new MySQLi. Please advise me how to modify this script, I would prefer the procedural style.
UPDATE - The MySQLi coding is not working because it would insert into the database like the MySQL coding would, would appreciate if your can help me.
MYSQL
<?php
error_reporting(1);
$submit = $_POST['submit'];
//form data
$name = mysql_real_escape_string($_POST['name']);
$name2 = mysql_real_escape_string($_POST['name2']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
$email2 = mysql_real_escape_string($_POST['email2']);
$address = mysql_real_escape_string($_POST['address']);
$address2 = mysql_real_escape_string($_POST['address2']);
$address3 = mysql_real_escape_string($_POST['address3']);
$address4 = mysql_real_escape_string($_POST['address4']);
$error = array();
if ($submit) {
//open database
$connect = mysql_connect("localhost", "root", "Passw0rd") or die("Connection Error");
//select database
mysql_select_db("logindb") or die("Selection Error");
//namecheck
$namecheck = mysql_query("SELECT * FROM users WHERE email='{$email}'");
$count = mysql_num_rows($namecheck);
if($count==0) {
}
else
{
if($count==1) {
$error[] = "<p><b>User ID taken. Try another?</b></p>";
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
$error[] = "<p><b>Password must be least 8 characters</b></p>";
}
if(!preg_match("#[A-Z]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 upper case characters</b></p>";
}
if(!preg_match("#[0-9]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 number</b></p>";
}
if(!preg_match("#[\W]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 symbol</b></p>";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
if($_POST['password'] != $_POST['password2']) {
$error[] = "<p><b>Password does not match</b></p>";
}
//rescue email match check
if($_POST['email2'] == $_POST['email']) {
$error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>";
}
//generate random code
$random = rand(11111111,99999999);
//check for error messages
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//Registering to database
$queryreg = mysql_query("INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysql_insert_id();
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
MYSQLI (NOT WORKING)
<?php
error_reporting(1);
$submit = $_POST['submit'];
//form data
$name = mysqli_real_escape_string($connect, $_POST['name']);
$name2 = mysqli_real_escape_string($connect, $_POST['name2']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$password2 = mysqli_real_escape_string($connect, $_POST['password2']);
$email2 = mysqli_real_escape_string($connect, $_POST['email2']);
$address = mysqli_real_escape_string($connect, $_POST['address']);
$address2 = mysqli_real_escape_string($connect, $_POST['address2']);
$address3 = mysqli_real_escape_string($connect, $_POST['address3']);
$address4 = mysqli_real_escape_string($connect, $_POST['address4']);
$error = array();
if ($submit) {
//open database
$connect = mysqli_connect("localhost", "root", "Passw0rd", "logindb") or die("Connection Error");
//namecheck
$namecheck = mysqli_query($connect, "SELECT * FROM users WHERE email='{$email}'");
$count = mysqli_num_rows($namecheck);
if($count==0) {
}
else
{
if($count==1) {
$error[] = "<p><b>User ID taken. Try another?</b></p>";
}
}
//check for existance
if($name&&$name2&&$email&&$password&&$password2&&$email2&&$address&&$address2&&$address3&&$address4) {
if(strlen($password)<8) {
$error[] = "<p><b>Password must be least 8 characters</b></p>";
}
if(!preg_match("#[A-Z]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 upper case characters</b></p>";
}
if(!preg_match("#[0-9]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 number</b></p>";
}
if(!preg_match("#[\W]+#",$password)) {
$error[] = "<p><b>Password must have at least 1 symbol</b></p>";
}
//encrypt password
$password = sha1($password);
$password2 = sha1($password2);
if($_POST['password'] != $_POST['password2']) {
$error[] = "<p><b>Password does not match</b></p>";
}
//rescue email match check
if($_POST['email2'] == $_POST['email']) {
$error[] = "<p><b>Rescue Email must not be the same as User ID</b></p>";
}
//generate random code
$random = rand(11111111,99999999);
//check for error messages
if(isset($error)&&!empty($error)) {
implode($error);
}
else
{
//Registering to database
$queryreg = mysqli_query($connect, "INSERT INTO users VALUES ('','$name','$name2','$email','$password','$password2','$email2','$address','$address2','$address3','$address4','$random','0')");
$lastid = mysqli_insert_id();
echo "<meta http-equiv='refresh' content='0; url=Activate.php?id=$lastid&code=$random'>";
die ();
}
}
}
?>
Converting to mysqli is not about adding i to the old library.
The main difference is that mysqli offers prepared statement feature.
This saves you from the tedious task of manually escaping values with mysqli_real_escape_string.
The proper way to do it is to prepare your query:
$query = "INSERT INTO users VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = mysqli_prepare($connect, $query)) {
mysqli_stmt_bind_param($stmt,'sssssssssssss', $name,$name2,$email,$password,$password2,$email2,$address,$address2,$address3,$address4,$random,'0');
/* execute prepared statement */
mysqli_stmt_execute($stmt);
/*Count the rows*/
if( mysqli_stmt_num_rows($stmt) > 0){
echo"New Record has id = ".mysqli_stmt_insert_id($stmt);
}else{
printf("Errormessage: %s\n", mysqli_error($connect));
die();
}
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
In addition to prepared statement, another advantage is the coding style, mysqli introduces OOP style, here is the same code in that style:
$query = "INSERT INTO users VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($stmt = $connect->prepare($query)) {
$stmt->bind_param('sssssssssssss', $name,$name2,$email,$password,$password2,$email2,$address,$address2,$address3,$address4,$random,'0');
/* execute query */
$stmt->execute();
/*Count the rows*/
if($stmt->num_rows > 0){
echo"New Record has id = ".$connect->insert_id;
}else{
var_dump($connect->error);
die();
}
/* close statement */
$stmt->close();
}
/* close connection */
$connect->close();
Both would achive the same. Good luck
I noticed one error in your script (mysqli script):
Instead of
$count = mysql_num_rows($namecheck);
do
$count = mysqli_num_rows($namecheck);
You can also check for errors in your query, like this (from w3schools - http://www.w3schools.com/php/func_mysqli_error.asp):
if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')"))
{
echo("Error description: " . mysqli_error($con));
}
Also try to do some debugging (echo some results) in your script to find errors.
Pass connection parameter inside
$lastid = mysqli_insert_id();
like
$lastid = mysqli_insert_id($connect);