I'm trying to use this code to be able to stop double bookings in my booking system. At the moment when you enter the same time twice then it comes up with this error:
Email is validthis time is already booked
Notice: Undefined variable: sql in C:\xampp\htdocs\book.php on line 44
Warning: mysqli_query(): Empty query in C:\xampp\htdocs\book.php on line 44
Error:
this is my code
<?php
//$error = ""; // Initialize error as blank
$con=mysqli_connect("localhost","","","");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$email = $_POST['email'];
$time = $_POST["time"];
$name = $_POST["name"];
$surname = $_POST["surname"];
$date = $_POST["date"];
$adl1 = $_POST["adl1"];
$adl2 = $_POST["adl2"];
$postcode = $_POST["postcode"];
if(!filter_var(($email), FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
}
else
{
echo "Email is valid";
$result = mysqli_query($con, "SELECT time FROM tbl_booking WHERE time = '$time'") or trigger_error("Query Failed! SQL: $result - Error: ".mysqli_error($con), E_USER_ERROR);
if(mysqli_num_rows($result) == 0)
{
$sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";
}
else
{
echo("this time is already booked");
}
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
}
Basically I think it's trying to access the $sql inside the if statement but I have no idea why it can't. Unless i'm being stupid.
You can rewrite your code as, since in else condition there is no query to the mysqli_query(), that why you got the error,
if(mysqli_num_rows($result) == 0){
$sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";
mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
} else {
echo("this time is already booked");
}
Set $sql as "global" -> you just need to create it before the if-statement.
Try to declare $sql value on top of your php code your code not execute
if(mysqli_num_rows($result) == 0)
{
$sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";
}
this condition its actually executing your else body that why it generate exception that $sql variable not defined
Related
0
I'm setting up the wholly organized sign up form, I'm trying to sent into information into my MySQL database server. My code not work and can't figuring out pops up message You have been signed up!
I've tried several options but none of them work on a server,
<?php
if (array_key_exists('email', $_POST) or array_key_exists('password', $_POST)) {
$link = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx");
if (mysqli_connect_error()) {
die("There was an error connecting to the database");
}
if ($_POST['email'] == '') {
echo "<p>Email address is required.</p>";
} else if ($_POST['password'] == '') {
echo "<p>Password is required.</p>";
} else {
$query = "SELECT `id` FROM `users` WHERE email = '" . mysqli_real_escape_string($link, $_POST['email']) . "'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
echo "<p>That email address has already been taken.</p>";
} else {
$query = "INSERT INTO `users` (`email`, `password`) VALUES ('" . mysqli_real_escape_string($link, $_POST['email']) . "', '" . mysqli_real_escape_string($link, $_POST['password']) . "')";
if (mysqli_query($link, $query)) {
echo "<p>You have been signed up!";
} else {
echo "<p>There was a problem signing you up - please try again later.</p>";
}
}
}
}
?>
When I signed up form only pops up "There was a problem signing you up - please try again later" I want to expect to "you have been signed up" from the result .
here is the problem
I'm a newbie in PHP. I wanted the display warning messages user to avoid entering duplicate values such as username, email and telephone number.
For example, user wants to change their username. When the user submit the form after editing their username, a warning message is display saying that username has already been taken or already exists.
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
include("../config.php");
include("../errors.php");
include("../success.php");
$errors = array();
$successes = array();
if ($_SESSION["uName"]){
if ($_SESSION["uType"] != "admin") {
header("location:../user/dashboard_user.php");
} else if ($_SESSION["uType"] == "admin"){
if(isset($_POST["update"])) {
$fname = $_POST["fname"];
$telno = $_POST["telno"];
$uname = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$password = md5($password);
$sql = "UPDATE users SET fullname = '$fname', telno = '$telno', username = '$uname', email = '$email', password = '$password' WHERE id = '".$_SESSION['uId']."'";
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
What is the correct way to use the SELECT statement in the code to get the expected results?
You should really handle the issue in the database:
create unique index idx_username on users(username);
Then in your code do what you do and then simply:
define('MYSQL_UNIQUE_CONSTRAINT_VIOLATION', 1062);
if (mysqli_query($con, $sql)) {
array_push($successes, "Update Success!");
} elsif (mysql_errno() == MYSQL_UNIQUE_CONSTRAINT_VIOLATION ) {
echo "Error: username $username is already taken";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
This code is very crude of course, but it gives you the idea. If your code inside the class, then use const instead of define.
Also, your code is very much liable to SQL injection. Use parametrised query instead of using variable inside the sql string.
The script doesn't throw any error, but if all the input fields are entered correctly, it just refreshs, and nothing happens.
I have included $salt and $link in header.php.
I might have overdid loops, but I spent couple of hrs trying to figure it out before posting it here.
<?php
if (array_key_exists('username', $_POST)||array_key_exists('pass', $_POST)||array_key_exists('email', $_POST)) {
if ($_POST["username"]!== "" && $_POST["email"]!== "" && $_POST["pass"]!== "" && $_POST['cpass']!== "" ){
if($_POST['pass']==$_POST['cpass']){
if (!mysqli_connect_error()) {
$query = "SELECT `username`, `email` FROM `users` WHERE `username` = '".mysqli_real_escape_string($link, $_POST['username'])."' OR `email` = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
if ($row = mysqli_fetch_array($result)) {
if ($row['username'] == $_POST['username']) {
echo "Username already exists!<br>";
//die("Awe! Someone took this username");
}
if ($row['email'] == $_POST['email']) {
echo "Email has been used once!<br>";
//die(":( Email is in use!");
}else if($row['username'] !== $_POST['username'] && $row['email'] !== $_POST['email']){
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
$query = "INSERT INTO `users`( `username`, `pass`, `email`) VALUES ('$username', '$pass', '$email')";
if(mysqli_query($link, $query)){
echo "You were successfully registered";
} else {
echo "Something went wrong, Couldn't register at the moment!";
}
}
}
}else{
echo "An Error Occured while connecting !";
}
}else {
echo "Password didn't match!";
}
}else{
echo "Field(s) can't be left blank!";
}
}
?>
The problem of your code happens on :
if ($row = mysqli_fetch_array($result)) {
and since you didn't place any else for this "if" you don't see anything happens.
The problem is, this condition becomes true only if email or username is already inside the table.
so if given username and/or email is not already in the table, this condition becomes false and therefore it never reaches to inside block where you want to insert the new data.
There is also a side issue with this and lets say your query fetch 2 rows.. imagine this table.
userid - username - email
1 - user1 - user1#test.com
2 - user2 - user2#test.com
now lets say the given input data are
$_POST['username'] = 'user1';
$_POST['email'] = 'user2#test.com';
this will fetch 2 rows in your users table, but as you didn't make a loop you will only check for first row and it might cause bug or unexpected behavior in your script.
UPDATE : I also made a piece of code based on your code.. hope it helps you...
function validateInputs(){
$keys = array('username','pass','cpass','email');
foreach($keys as $key){
if(!isset($_POST[$key]) || empty($_POST[$key])){
throw new Exception("Field(s) can't be left blank!");
}
}
}
function validatePassword(){
if($_POST['pass'] !== $_POST['cpass']){
throw new Exception("Password didn't match!");
}
}
function checkForUniqueInput($email,$username){
global $link;
$query = "SELECT username, email FROM users WHERE username = '".$username."' OR email = '".$email."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
throw new Exception("Username and/or email already exist");
}
}
function insertNewUser($email,$username,$pass){
global $link;
$query = "INSERT INTO users( username, pass, email) VALUES ('".$username."', '".$pass."', '".$email."')";
if(!mysqli_query($link, $query)){
throw new Exception("Something went wrong, Couldn't register at the moment!");
}
}
if(isset($_POST)){
try{
validateInputs();
validatePassword();
$email = mysqli_real_escape_string($link, $_POST["email"]);
$username = mysqli_real_escape_string($link, $_POST["username"]);
$pass = md5($salt.mysqli_real_escape_string($link, $_POST["pass"]));
checkForUniqueInput($email,$username);
insertNewUser($email,$username,$pass);
echo 'You were successfully registered';
}
catch(Exception $e){
echo 'Error : '.$e->getMessage();
}
}
I have a webform with basic info (Name, Last_Name, Date of Birth, Telephone, Email)
After submitting the form, and inserting the data of those fields into a MySQL database, I want to be able to be redirected to a different URL. I tried using the header function for php but for some reason it will not redirect me to the URL I specified.
<?php
if ($_POST) {
$host="23.229.187.201"; // Host name
$username="inturuser"; // Mysql username
$password="admin123"; // Mysql password
$db_name="intur"; // Database name
$tbl_name="test_mysql"; // Table name
// Connect to server and select database.
$link = mysql_connect("localhost", "inturuser", "hola123")or die("Error");
mysql_select_db("intur")or die("cannot select DB");
// Get values from form the form
$name=$_POST['name'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
$bday = date('Y-m-d', strtotime($_POST['bday']));
$phone = $_POST['phone'];
$datetime = date('Y-m-d H:i:s');
$ip = "";
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
// Insert data into mysql
$sql = 'INSERT INTO users (nombre, apellido, correo, fecha_nacimiento, telefono, ip_restaurante, timestamp)
VALUES("'.$name.'", "'.$lastname.'", "'.$email.'", "'.$bday.'", "'.$phone.'", "'.$ip.'", "'.$datetime.'")';
mysql_query($sql);
mysql_close();
// if successfully insert data into database, displays message "Successful and redirect to a URL ".
if($result)
{
header('Location: http://www.example.com/');;
}
else {
echo "ERROR";
}
//close connection
}
else {
echo "NO POST";
}
?>
You have not assigned the $result variable so the if($result) will always be false.
You should turn on your error_reporting to show E_NOTICE, and then you need to replace your mysql_query line with $result = mysql_query($sql).
Your code:
$sql = 'INSERT INTO users (nombre, apellido, correo, fecha_nacimiento, telefono, ip_restaurante, timestamp)
VALUES("'.$name.'", "'.$lastname.'", "'.$email.'", "'.$bday.'", "'.$phone.'", "'.$ip.'", "'.$datetime.'")';
mysql_query($sql);
mysql_close();
// if successfully insert data into database, displays message "Successful and redirect to a URL ".
if($result)
{
header('Location: http://www.example.com/');;
}
please remove extra semicolon from header. and assign $result=mysql_query($sql)
corrected solution:
$sql = 'INSERT INTO users (nombre, apellido, correo, fecha_nacimiento, telefono, ip_restaurante, timestamp)
VALUES("'.$name.'", "'.$lastname.'", "'.$email.'", "'.$bday.'", "'.$phone.'", "'.$ip.'", "'.$datetime.'")';
$result=mysql_query($sql);
mysql_close();
// if successfully insert data into database, displays message "Successful and redirect to a URL ".
if($result)
{
header('Location: http://www.example.com/');
}
Problem:
Trying to run two MySQLi queries against the database but results always into a failure message.
Code (PHP):
// Checks whether submit button has been pressed
if (isset($_POST['submit']))
{
// Gets values from form fields
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
// Selects e-mail in database
$query = "SELECT * FROM userlogin WHERE email = '{$email}'";
$result = mysqli_query($link, $query) or die('Error [' . mysqli_error($link) . ']');
// Checks whether e-mail exist
if (mysqli_num_rows($result) != 0)
{
// Register new user
$query = "INSERT INTO
userlogin
(username, password, email, regdate)
VALUES
('James','{$password}', '{$email}', NOW())
";
// Submit query to database
$result = mysqli_query($link, $query) or die('Error [' . mysqli_error($link) . ']');
// Return success message
header('Location: index.php?notification=success');
}
else
{
// Return failure message
header('Location: index.php?notification=fail');
}
}
What am I missing? Any advice is appreciated.
Shouldn't this
mysqli_num_rows($result) != 0
be
mysqli_num_rows($result) == 0
One issue is
$email = mysql_real_escape_string(stripslashes($_POST['email']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
and should be
$email = mysqli_real_escape_string($link,stripslashes($_POST['email']));
$password = mysqli_real_escape_string($link,stripslashes($_POST['password']));