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
}
Related
I had created a database which named student with ID, name, mat_number, specialty, age, and gender, in a PHP application.
I do not want the name or mat_number be taken in more than once.
I have done the connection to my database in a different page and called it in the add student page.
This following codes is for a faculty database collection
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender))
{
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}
else{
echo "Error: Complete all records";
}
}
?>
I want to get an error message demanding for a change if the 2 fields already exist in the database.
first name to check in database if already exist the record.
if no record run sql insert command.
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
$sql = "SELECT * FROM `student` WHERE name = "'.$name.'" and UB_number = '".$matNo."'";
$conn->query($sql);
$cnt = $conn->rowCount();
if($cnt == 0){
$sql = "INSERT INTO `student`
(`name`, `UB_number`, `age`,`sex`, `specialty`)
VALUES
('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}else{
echo "Error: Complete all records";
}
}
If you would like to insert a new record to DB only if one doesn't exist which has the same name or mat_number then you first need to execute SELECT statement to see if it exists.
Using MySQLi:
<?php
include 'mysqli.php';
$conn = $mysqli;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->bind_param('ss', $name, $matNo);
$stmt->execute();
$stmt->bind_result($exists);
$stmt->fetch();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)');
$stmt->bind_param('sssss', $name, $matNo, $age, $gender, $specialty);
$stmt->execute();
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
Using PDO:
<?php
include 'lib.php';
$conn = $pdo;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->execute([$name, $matNo]);
$exists = $stmt->fetchColumn();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)')
->execute([$name, $matNo, $age, $gender, $specialty]);
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
hope this may be helpfull to you. In here I asume that you are not using any framework. But if you use a framework there are plenty of easy methods to do this.In here I have checked only name field. You should update code as you wants. Also it it better if you could validate your inputs before check. Like trim(). Thanks
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
//after user click the submit button
$sql_Select_Stundets = "SELECT * FROM student WHERE name = '$name' ";
// query the sql with db connection
$result_sql_Select_Stundets = mysqli_query($conn,$sql_Select_Stundets);
//Now check the row count to verify the output if there is any match
$rowcount=mysqli_num_rows($result);
//Now write insert inside if condition
if( $rowcount >0 ) {
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender)) {
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
bheader("Location: index.php");
}else{
echo "Error: Complete all records";
}
}else{
echo "<script>
alert('sorry this name is already available');
</script>";
}
}
?>
I'm trying to use this php document to use a form to input information into a database. I keep getting the same error, Column 'custID' cannot be null. I don't know whats wrong or what to do. I might have to take the L for this assignment but it would be helpful if I could get an answer in case I run into the same problem in the future.
I already tried doing NOT NULL AUTO_INCREMENT in the mysql code. i also tried doing the same thing by using NULL for custID. Neither worked.
if(isset($_POST['submit'])){
$data_missing = array();
if(empty($_POST['custID'])){
$data_missing[] = 'Customer ID';
}else{
$custID = trim($_POST['custID']);
}
if(empty($_POST['custFirstName'])){
$data_missing[] = 'First Name';
}else{
$custFirstName = trim($_POST['custFirstName']);
}
if(empty($_POST['custLastName'])){
$data_missing[] = 'Last Name';
}else{
$custLastName = trim($_POST['custLastName']);
}
if(empty($_POST['address'])){
$data_missing[] = 'Address';
}else{
$address = trim($_POST['address']);
}
if(empty($_POST['city'])){
$data_missing[] = 'city';
}else{
$city = trim($_POST['city']);
}
if(empty($_POST['custstate'])){
$data_missing[] = 'State';
}else{
$custstate = trim($_POST['custstate']);
}
if(empty($_POST['custEmail'])){
$data_missing[] = 'Email';
}else{
$custEmail = trim($_POST['custEmail']);
}
if(empty($_POST['custPhone'])){
$data_missing[] = 'Phone';
}else{
$custPhone = trim($_POST['custPhone']);
}
if(empty($_POST['Password'])){
$data_missing[] = 'Password';
}else{
$Password = trim($_POST['Password']);
}
}
if(empty($data_missing)){
require_once '../LabYourLastProject/mysqli_connect.php';
$query = "INSERT INTO Customers (custID, custFirstName, custLastName, address, city,"
. " custstate, custEmail, custPhone, Password) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "sssssssss", $custID, $custFirstName,$custLastName, $address, $city, $custstate, $custEmail, $custPhone, $Password);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
if($affected_rows == 1){
echo 'Student Entered';
mysqli_stmt_close($stmt);
mysqli_close($dbc);
}else{
echo 'Error Occurred <br />';
echo mysqli_error($dbc);
}
}else{
echo'You need to enter the following data<br />';
foreach($data_missing as $missing){
echo "$missing<br />";
}
}
Its supposed to insert the data passed from the form in another file into a database and show what data is missing. I just get the error.
You have to remove custID because is an AUTO_INCREMENT
$query = "INSERT INTO Customers (custFirstName, custLastName, address, city,"
. " custstate, custEmail, custPhone, Password) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
and this code
mysqli_stmt_bind_param($stmt, "sssssssss", $custFirstName,$custLastName, $address, $city, $custstate, $custEmail, $custPhone, $Password);
When inserting data to a database table the primary key which for your case is custID needs to be left out as it is not necessary here. It will be taken care by the server. Good thing you have put it to be auto_increment. You can include it in your insert code only when you have a value that is unique. But under normal circumstance leave it blank and insert other fields
$query = "INSERT INTO Customers (custFirstName, custLastName, address, city,"
. " custstate, custEmail, custPhone, Password) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
I am trying to avoid duplicate entries of automatically generated random numbers in an SQLite3 DB through PHP. For that i have prepared Statements in a do while loop. The random numbers are generated and then a query checks if the number already exists. If Yes, generate again, if no, carry on.
Atleast, this is what i am trying to achieve...
But for some reason unknown to me, the PHP log keeps showing me that the maximum execution Time of 30 secs has been exeeded at the query line. Firstly, i tried doing the whole thing without prepared statements and it didn't work. I thought that was because i had php variables in the query. So i switched to Prepared Statements without success.
I checked all the POST Variables via Firebug and everything seems to be fine there. It is the Prepared Statement which is giving me diarrhea!!
Can you guys please help me ?
The PHP Code:
<?php
$adate = $_POST['adate'];
$ddate = $_POST['ddate'];
$ad = $_POST['ad'];
$dd = $_POST['dd'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$address = $_POST['address'];
$postal = $_POST['postal'];
$city = $_POST['city'];
$country = $_POST['country'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$price = $_POST['price'];
$bkfst = $_POST['bkfst'];
$rnum = $_POST['rnum'];
$rtype = $_POST['rtype'];
$robotest = $_POST['blnk'];
$bid = 0;
$cid = 0;
$adate = $adate . " 20:00:00";
$ddate = $ddate . " 13:00:00";
if ($robotest)
$error = "You are a gutless robot.";
else {
function bid()
{
$bid = mt_rand(111111, 999999);
if (($bid % 10) == 0) {
$bid = $bid + 123;
}
}
function cid()
{
$cid = mt_rand(11111, 99999);
if (($cid % 10) == 0) {
$cid = $cid + 123;
}
}
include 'connect.php';
do {
cid();
--> $sth = $db->prepare("SELECT COUNT (CustomerID) from Customer WHERE CustomerID = ?");
$sth->execute(array($cid));
} while ($sth->fetchColumn() > 0);
$sth = $db->prepare("INSERT INTO Customer (CustomerID, FirstName, LastName, Address, PostalCode, City, Country, EMail, Phone) VALUES ('$cid', '$fname', '$lname', '$address', '$postal', '$city', '$country', '$email', '$tel')");
$sth->execute();
do {
bid();
--> $sth = $db->prepare("SELECT COUNT (BookingID) from Booking WHERE BookingID = ?");
$sth->execute(array($bid));
} while ($sth->fetchColumn() > 0);
$sth = $db->prepare("INSERT INTO Booking (BookingID, Arrival, Checkout, RoomNumber, CustomerID, Breakfast, Comment, Paid) VALUES ('$bid', '$adate', '$ddate', '$rnum', '$cid', '$bkfst', '$message', 'N')");
$sth->execute();
$subject = "Your Booking";
$message = "Hi $fname,\n\nA $rtype from $ad to $dd has been booked for you.\n\nYour Booking Code is $bid.\n\nRegards.";
mail($email, $subject, $message);
echo 'The Booking completed successfully! Check your E-Mail for further Information.';
}
?>
Lines beginning with --> in the code are the problematic lines.
And Yes, I am a Newbie who is learning by doing and also learning by annoying people in the Stack Overflow Forums :)
Thanks.
EDIT:
This is how my Code looks now. All the errors are gone but php is not inserting anything to the DB. The Email is sent correctly with the generated number.
<?php
$adate = $_POST['adate'];
$ddate = $_POST['ddate'];
$ad = $_POST['ad'];
$dd = $_POST['dd'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$address = $_POST['address'];
$postal = $_POST['postal'];
$city = $_POST['city'];
$country = $_POST['country'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$price = $_POST['price'];
$bkfst = $_POST['bkfst'];
$rnum = $_POST['rnum'];
$rtype = $_POST['rtype'];
$robotest = $_POST['blnk'];
$adate = $adate . " 20:00:00";
$ddate = $ddate . " 13:00:00";
$cid;
$bid;
if ($robotest)
$error = "You are a gutless robot.";
else {
function bid()
{
global $bid;
$bid = mt_rand(111111, 999999);
if (($bid % 10) == 0) {
$bid = $bid + 123;
}
}
function cid()
{
global $cid;
$cid = mt_rand(11111, 99999);
if (($cid % 10) == 0) {
$cid = $cid + 123;
}
}
include 'connect.php';
do {
global $cid;
cid();
$sth = $db->prepare('SELECT COUNT (CustomerID) from Customer WHERE CustomerID = ?');
$sth->execute(array($cid));
} while ($sth->fetchColumn() > 0);
global $cid;
$sth = $db->prepare('INSERT INTO Customer (CustomerID, FirstName, LastName, Address, PostalCode, City, Country, EMail, Phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
$sth->execute(array($cid, $fname, $lname, $address, $postal, $city, $country, $email, $tel));
do {
global $bid;
bid();
$sth = $db->prepare('SELECT COUNT (BookingID) from Booking WHERE BookingID = ?');
} while ($sth->fetchColumn() > 0);
global $bid;
global $cid;
$sth = $db->prepare('INSERT INTO Booking (BookingID, Arrival, Checkout, RoomNumber, CustomerID, Breakfast, Comment, Paid) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
$sth->execute(array($bid, $adate, $ddate, $rnum, $cid, $bkfst, $message, 'N'));
$subject = "Your Booking";
global $bid;
$message = "Hi $fname,\n\nA $rtype from $ad to $dd has been booked for you.\n\nYour Booking Code is $bid.\n\nRegards.";
mail($email, $subject, $message);
echo 'The Booking completed successfully! Check your E-Mail for further Information.';
}
?>
hhmmm...
This is an infinite loop:
do {
cid();
$sth = $db->prepare("SELECT COUNT (CustomerID) from Customer WHERE CustomerID = ?");
$sth->execute(array($cid));
} while ($sth->fetchColumn() > 0);
Since your cid/bid() functions are badly constructed, the $cid you're using inside this do() loop will NEVER change from the $cid = 0 you did at the top of the script.
So the loop starts, you prepare/execute the query with CustomerID = 0, get back one of row of data with the count() results, which you fetch.
Then the loop rolls around again, and you RE-EXECUTE the query, with the exact same $cid = 0 value, so you continue reset the loop termination condition - you never end up with a value, because you keep query with the same bad/invalid cid=0.
It's pretty much the same like the good old BASIC program: 10 GOTO 10.
It's working now:
<?php
$adate = $_POST['adate'];
$ddate = $_POST['ddate'];
$ad = $_POST['ad'];
$dd = $_POST['dd'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$address = $_POST['address'];
$postal = $_POST['postal'];
$city = $_POST['city'];
$country = $_POST['country'];
$tel = $_POST['tel'];
$message = $_POST['message'];
$price = $_POST['price'];
$bkfst = $_POST['bkfst'];
$rnum = $_POST['rnum'];
$rtype = $_POST['rtype'];
$robotest = $_POST['blnk'];
$adate = $adate . " 20:00:00";
$ddate = $ddate . " 13:00:00";
$cid;
$bid;
if ($robotest)
$error = "You are a gutless robot.";
else {
function bid()
{
global $bid;
$bid = mt_rand(111111, 999999);
if (($bid % 10) == 0) {
$bid = $bid + 123;
}
}
function cid()
{
global $cid;
$cid = mt_rand(11111, 99999);
if (($cid % 10) == 0) {
$cid = $cid + 123;
}
}
include 'connect.php';
$sth = $db->prepare('SELECT COUNT (EMail) from Customer WHERE EMail = ?');
$sth->execute(array($email));
if($sth->fetchColumn() < 1){
do {
global $cid;
cid();
$sth = $db->prepare('SELECT COUNT (CustomerID) from Customer WHERE CustomerID = ?');
$sth->execute(array($cid));
} while ($sth->fetchColumn() > 0);
global $cid;
$sth = $db->prepare('INSERT INTO Customer (CustomerID, FirstName, LastName, Address, PostalCode, City, Country, EMail, Phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
$sth->execute(array($cid, $fname, $lname, $address, $postal, $city, $country, $email, $tel));
}else{
global $cid;
$sth = $db->prepare('SELECT CustomerID from Customer WHERE EMail = ?');
$sth->execute(array($email));
$id = $sth->fetch(PDO::FETCH_ASSOC);
$cid = $id['CustomerID'];
}
do {
global $bid;
bid();
$sth = $db->prepare('SELECT COUNT (BookingID) from Booking WHERE BookingID = ?');
} while ($sth->fetchColumn() > 0);
global $bid;
global $cid;
$booktime = date('Y-m-d H:i:s');
$sth = $db->prepare('INSERT INTO Booking (BookingID, Arrival, Checkout, RoomNumber, CustomerID, Breakfast, Comment, Paid, BookTime, Invoice) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$sth->execute(array($bid, $adate, $ddate, $rnum, $cid, $bkfst, $message, 'N', $booktime, NULL));
$subject = "Your Booking";
global $bid;
$message = "Hi $fname,\n\nA $rtype from $ad to $dd has been booked for you.\n\nYour Booking Code is $bid.\n\nMention this Code if you need to get in touch with us.\n\nRegards.";
mail($email, $subject, $message);
echo 'The Booking completed successfully! Check your E-Mail for further Information.';
}
?>
No Clue, if this is the best way to do it but it is working perfectly.
Thanks for all the hints.
I am getting this error when I submit the form.
call to a member function bind_param() on a non-object
I have checked the console as well. It shows all the values I enter in the form. The values are getting stored in json variable and passed to the php page.It is on the bind_param() function, it shows the error. The same code works for the remaining 2 pages of my project, but it is not working for this one. Please help
Here is the PHP code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "kites";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
alert("Connection failed");
}
else
{
// Check for empty fields
if(
empty($_POST['username']) || empty($_POST['password']) || empty($_POST['firstname']) || empty($_POST['lastname']) || empty($_POST['age']) || empty($_POST['contact']) || empty($_POST['streetname']) || empty($_POST['buildingname']) || empty($_POST['landmark']) || empty($_POST['area']) || empty($_POST['pincode']) || empty($_POST['email']) || empty($_POST['univ']) || empty($_POST['qualification']) || empty($_POST['dialcode']) || empty($_POST['countrycode']) || empty($_POST['bloodgroup']) || empty($_POST['school'])
)
{
echo json_encode(array('status'=>false,'msg'=>'No arguments provided'));
}
else if(is_numeric($_POST['firstname']) && is_numeric($_POST['lastname']))
{
echo json_encode(array('status'=>false,'msg'=>'Name should not contain numbers. Please try again'));
}
else if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
echo json_encode(array('status'=>false,'msg'=>'Check your email id and try again'));
}
else if(!is_numeric($_POST['age']))
{
echo json_encode(array('status'=>false,'msg'=>'Age should contain only numbers'));
}
else{
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$bloodgroup = $_POST['bloodgroup'];
$contact = $_POST['contact'];
$streetname = $_POST['streetname'];
$buildingname = $_POST['buildingname'];
$landmark = $_POST['landmark'];
$area = $_POST['area'];
$pincode = $_POST['pincode'];
$email = $_POST['email'];
$univ = $_POST['univ'];
$school = $_POST['school'];
$qualification = $_POST['qualification'];
$dialcode = $_POST['dialcode'];
$countrycode = $_POST['countrycode'];
// $sql = "INSERT INTO join_form (name,email,contact,role,dialcode,countrycode) VALUES ('$name','$email','$contact','$role','$dialcode','$countrycode')";
$stmt = $conn->prepare("INSERT INTO register_form(username,password,firstname,lastname,age,bloodgroup,contact,streetname,buildingname,landmark,area,pincode,email,univ,school,qualification,dialcode,countrycode) VALUES(?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssisssssssssssss",$username,$password,$firstname,$lastname,$age,$bloodgroup,$contact,$streetname,$buildingname,$landmark,$area,$pincode,$email,$univ,$school,$qualification,$dialcode,$countrycode);
$sql = $stmt->execute();
if ($sql) {
echo json_encode(array('status'=>true,'msg'=>"New record created successfully"));
// // Create the email and send the message
// $to = 'naitikgada1995#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
// $email_subject = "Registration Successfull: $name";
// $email_body = "We have sent this mail to inform you that your registration is successfull\n\n"
// ."Here are the details:\n\n"
// ."Name: $name\n\nEmail: $email\n\nContact:$contact\n\nPassword: $password\n\n";
// $headers = "From: noreply#kiddo.com\n";
// $headers .= "Reply-To: $email";
// mail($to,$email_subject,$email_body,$headers);
// // $response['status'] = 'true';
}
else {
echo json_encode(array('status'=>false,'msg'=>'Enter different email id or contact number and try again'));
// return false;
// $response['feedback'] = 'false';
// $response['message'] = 'Sorry, something went wrong. Please try again. Try entering a different email id and contact number';
// echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// header("Content-Type: application/json; charset=utf-8", true);
}
}
?>
see if there is any spelling mistake or any other error in this line in the query
$stmt = $conn->prepare("INSERT INTO register_form(username,password,firstname,lastname,age,bloodgroup,contact,streetname,buildingname,landmark,area,pincode,email,univ,school,qualification,dialcode,countrycode) VALUES(?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?)");
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);