Prepared Statement (PHP5, SQLite3) exceeds 30 seconds execution Time - php

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.

Related

Adding multiple entries to a table

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
}

Inserting data in diferent tables

Im trying to add data to diferent tables in MySQL, but at the moment of run my code, it shows me a error is it "Fatal error: Uncaught Error: Call to a member function query()", is the firs time that y use the query function so I don't know whats going wrong.
<?php
session_start();
$_SESSION['ID_user'];
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = '$id' LIMIT 1");
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "UPDATE user SET Name_user='$name', password='$password' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->bindParam(':name', $_POST['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $result['name'];
$lastid = $conn->query("SELECT last_insert_id()")->fetch();
$insert = "INSERT INTO rel_company_user (ID_user) VALUES ('$id')";
$in = $conn->prepare($insert);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES ('$company')";
$in = $conn->prepare($insert);
$in->execute();
$update = "UPDATE rel_company_user SET ID_company='$lastid' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>
You should use parameters in all your queries. And you can't use bindParam() if you didn't put a placeholder in the query.
FILTER_SANITIZE_SPECIAL_CHARS is not a valid argument to bindParam(). The third argument is an optional data type.
You never set $thelast anywhere, that should be $conn.
If $id is already assigned, you can't use LAST_INSERT_ID() to get ID_user. Just insert that value into the user table.
You don't need to perform a query to get the last insert ID. Just use LAST_INSERT_ID() in the VALUES list of the next INSERT query.
You can't fetch the results of an UPDATE query.
You can't get the last insert ID if you haven't done an insert. The UPDATE user query should be INSERT INTO user.
In several places you assigned the SQL to $insert, but then did $conn->prepare($update).
<?php
session_start();
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = :id LIMIT 1");
$resultset->bindParam(':id', $id);
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "INSERT INTO user (ID_user, Name_user, password) VALUES (:id, :name, :password)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->bindParam(':name', $name);
$up->bindParam(':password', $password);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $name;
$insert = "INSERT INTO rel_company_user (ID_user) VALUES (:id)";
$in = $conn->prepare($insert);
$in->bindParam(':id', $id);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES (:company)";
$in = $conn->prepare($insert);
$in->bindParam(':company', $company);
$in->execute();
$update = "INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), :id)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>

preventing duplicate row data entries

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>";
}
}
?>

Passing userID into booking table

I have a user table that links to a booking table so I can tell what users have made what bookings. I have tried to left join the user table with the booking table but it didn't work. I also experimented with trying to pass the session userID but again it didn't work. My PHP code is presented below that I'm trying to pass through at the minute.
<?php
include "config.php";
//Booking point
if(isset($_POST['booking']))
{
//get values for variables
$pitchID = $_POST['pitchID'];
$start_date = $_POST['start_date'];
$start_hour = $_POST['start_hour'];
$end_hour = $_POST['end_hour'];
$booking_age = $_POST['booking_age'];
$pitch_size = $_POST['pitch_size'];
$light_tokens = $_POST['light_tokens'];
$q = $db->prepare("SELECT *
FROM booking
LEFT JOIN user
ON booking.userID=user.userID");
$query = $q-> execute();
if($query)
{
$q = $db->prepare("INSERT INTO booking SET pitchID = ?, start_date = ?, start_hour = ?, end_hour = ?, booking_age = ?, pitch_size = ?, light_tokens = ?");
$query = $q->execute(array($pitchID,$start_date,$start_hour,$end_hour,$booking_age,$pitch_size,$light_tokens));
$count = $q->rowCount();
if($count == 1){
echo "Your booking has been made";
header("Location:home2_template.html");
return;
}else {
echo "Fail";
}
} else {
echo"Booking already exists";
}
}
?>
I added the session variable in the login section of my system then passed it through from there.
Login section below:
<?php
include "config.php";
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$q = $db->prepare("SELECT * FROM user WHERE username = ? AND password = ?");
$query = $q->execute(array($username, $password));
while($dbRow = $q->fetch(PDO::FETCH_ASSOC)) {
$userID = $dbRow['userID'];
}
$count = $q->rowCount();
if($count == 1){
session_start();
$_SESSION['userID'] = $userID;
header("Location:home2_template.html");
return;
}else{
echo "You have entered an incorrect login/password";
}
}
?>
I also removed the join in the PHP code and ended up with this below. It passed through my userID but there are still bugs in this code for anyone who is viewing this. I had to declare the variable userID at the top of my page then again in my prepare statement.
<?php
session_start();
$userID = $_SESSION['userID'];
?>
<?php
include "config.php";
echo $userID;
//Booking point
if(isset($_POST['booking']))
{
//get values for variables
$pitchID = $_POST['pitchID'];
$start_date = $_POST['start_date'];
$start_hour = $_POST['start_hour'];
$end_hour = $_POST['end_hour'];
$booking_age = $_POST['booking_age'];
$pitch_size = $_POST['pitch_size'];
$light_tokens = $_POST['light_tokens'];
$q = $db->prepare("INSERT INTO booking SET pitchID = ?, start_date = ?, start_hour = ?, end_hour = ?, booking_age = ?, pitch_size = ?, light_tokens = ?, userID='$userID'");
$query = $q->execute(array($pitchID,$start_date,$start_hour,$end_hour,$booking_age,$pitch_size,$light_tokens));
$count = $q->rowCount();
if($count == 0)
{
echo "Your booking has been made";
header("Location:home2_template.html");
return;
}else {
echo "That booking already exists";
}
}
?>

Can't get PHP rest server post method to update database

I am creating an android app with a php Rest server with firebird database. I can get information from the database via json with php server but I can't update anything. Here is my code.
public function update_user_info (){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$home = $_POST['home'];
$cell = $_POST['cell'];
$birthdate = $_POST['birthdate'];
$weekly = $_POST['weekly'];
$email = $_POST['email'];
$users_id = $_POST[users_id];
$last_active = date("m/d/Y", time());
$last_act_time = date("h:i:s", time());
$acct_email = strtolower($email);
//make email all lowercase
horse_connect();
$query = ibase_prepare("UPDATE USERS SET FIRST_NAME = ?,
LAST_NAME = ?, ADDRESS = ?, CITY = ?,
STATE = ?, ZIP = ?, HOME_PHONE = ?, CELL_PHONE = ?,
BIRTHDATE = ?, HTML_EMAIL = ?,
LAST_ACTIVE = ?,
LAST_ACT_TIME = ?, EMAIL_NEWS = ?, EMAIL_LIVE_SCORES = ?
WHERE USERS_ID = ?");
$result = ibase_execute($query, $fname, $lname,
$address, $city, $state, $zip,
$home, $cell, $birthdate,
$acct_email, $last_active, $last_act_time,
$weekly, $live, $users_id);
//$final_array = array('user id' => $fname);
if($Result)
$json = array("status" => 1);
else
$json = array("status" =>0);
echo json_encode($json);
} //end: update_user_info
I am using Advanced rest client for testing.
Try using ibase_commit after execute. If possible try to use PDO when working with database.
Thanks everyone but I found the Problem. HTML_EMAIL should be ACCT_EMAIL. HTML_EMAIL is a bit field, true or false. ACCT_EMAIL is a string

Categories