SQL INSERT doens't insert, without any error - php

I am making a hotel booking system for a school project.
Guests first need to create an account:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$signupdate = mysqli_real_escape_string($conn, $_POST['signupdate']);
$first = mysqli_real_escape_string($conn, $_POST['firstname']);
$last = mysqli_real_escape_string($conn, $_POST['lastname']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$phone = mysqli_real_escape_string($conn, $_POST['phone']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$hoteluserkey = uniqid('', true);
//Error handlers
//Check for empty fields
if (empty($signupdate) || empty($first) || empty($last) || empty($email) || empty($phone) || empty($address) || empty($pwd)) {
header("Location: ../index.php?signup=empty");
exit();
} else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $first) || !preg_match("/^[a-zA-Z]*$/", $last)) {
header("Location: ../index.php?signup=invalid");
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../index.php?signup=invalidemail");
exit();
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the database
$sql = "INSERT INTO hotelusers
(hotelusers_signupdate, hotelusers_hoteluserkey, hotelusers_first, hotelusers_last, hotelusers_email, hotelusers_phone, hotelusers_address, hotelusers_pwd)
VALUES ('$signupdate', '$hoteluserkey', '$first', '$last', '$email', '$phone', '$address', '$hashedPwd');";
mysqli_query($conn, $sql);
header("Location: ../index.php?signup=success");
exit();
}
}
}
} else {
header("Location: ../index.php");
exit();
}
This code works.
Now to problem comes. When someone books a room they see these input fields:
<div class="book">
<p class="main_p_ex">Book a room</p>
<form class="book" action="includes/book.inc.php" method="post">
<input type="hidden" name="bookdate" value="<?php echo date("Y-m-d h:i:sa"); ?>">
<input type="text" name="userkey" placeholder="your key">
<input type="password" name="pwd" placeholder="password">
<p>room</p>
<select name="room">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
<option value="8">eight</option>
<option value="9">nine</option>
<option value="10">ten</option>
</select>
<p>from</p>
<input type="date" name="from" min="<?php echo date("Y-m-d");?>">
<p>to</p>
<input type="date" name="to" min="<?php echo date("Y-m-d");?>">
<textarea name="otherguests" placeholder="full names of all other
guests"></textarea>
<textarea name="comments" placeholder="any comments?"></textarea>
<button type="submit" name="submit">Book!</button>
</form>
</div>
This also works fine.
I have this code for inserting these inputs into a database:
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$bookdate = mysqli_real_escape_string($conn, $_POST['bookdate']);
$userkey = mysqli_real_escape_string($conn, $_POST['userkey']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$room = mysqli_real_escape_string($conn, $_POST['room']);
$from = mysqli_real_escape_string($conn, $_POST['from']);
$to = mysqli_real_escape_string($conn, $_POST['to']);
$otherguests = mysqli_real_escape_string($conn, $_POST['otherguests']);
$comments = mysqli_real_escape_string($conn, $_POST['comments']);
$bookingkey = uniqid('', true);
//Error handlers
//Check if inputs are empty
if (empty($userkey) || empty($pwd) || empty($room) || empty($from) || empty($to) || empty($pwd)) {
header("Location: ../index.php?login=empty");
exit();
} else {
$sql = "SELECT * FROM hotelusers WHERE hotelusers_hoteluserkey='$userkey'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck < 1) {
header("Location: ../index.php?key=error");
exit();
} else {
if ($row = mysqli_fetch_assoc($result)) {
//De-hashing the password
$hashedPwdCheck = password_verify($pwd, $row['hotelusers_pwd']);
if ($hashedPwdCheck == false) {
header("Location: ../index.php?key=error");
exit();
} elseif ($hashedPwdCheck == true){
$sql = "SELECT * FROM hotelrooms WHERE hotelrooms_id='$room'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$roomnew = $row['hotelrooms_name']; }
}
$fromnew = strtotime($from);
$tonew = strtotime($to);
$datediff = $tonew - $fromnew;
$days = round($datediff / 86400);
$sql = "SELECT * FROM hotelrooms WHERE hotelrooms_id='$room'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$pricepd = $row['hotelrooms_price']; }
}
$price = $days * $pricepd;
echo $roomnew . " -- " . $price . " -- " . $days . " -- " . $bookdate . " -- " . $userkey . " -- " . $room . " -- " . $otherguests . " -- " . $comments;
$sql = "INSERT INTO hotelbookings
(hotelbooking_bookingkey, hotelbooking_bookdate, hotelbooking_userkey, hotelbooking_room, hotelbooking_from, hotelbooking_to, hotelbooking_days, hotelbooking_price, hotelbooking_paid, hotelbooking_otherguests, hotelbooking_comments)
VALUES ('$bookingkey', '$bookdate', '$userkey', '$roomnew', '$from', '$to', '$days', '$price', '$otherguests', '$comments');";
mysqli_query($conn, $sql);
//header("Location: ../index.php?booking=success");
exit();
}
}
}
}
} else {
header("Location: ../index.php?booking=error");
exit();
}
NOTE: I disabled the last header function for debugging. Un-commenting it changes nothing. Also tried clearing browser history, cookies and all that. Nothing works.
What am I missing here?
I don't get any errors, and the echo $roomnew . " -- " . $price . " -- " . $days . " -- " . $bookdate . " -- " . $userkey . " -- " . $room . " -- " . $otherguests . " -- " . $comments; works fine. It just doesn't insert anything.

solved it myself by just making everything again... kinda weird I know

Related

Adding points and then show balance

I have something like this on my website. and I want to calculate the whole points of Sofia and show her the total balance. which is 163. but I am not getting how to add and then show her balance on my website. sorry, if it is too easy question. I am new to php.
here is the code
<form method="POST">
user name : <input type="text" name="username"><br>
Points to Add: <input type="number" name="blance" max="100"
min="1">
<br>
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$user = "root";
$password = "";
$database = "enter code here";
$con = mysqli_connect("$servername", "$user" , "$password" ,
"$database");
if ($con->connect_error) {
die ("connection failed" . $con->connect_error);
} else {
$username = mysqli_real_escape_string($con, $_POST['username']);
$blance = mysqli_real_escape_string($con, $_POST['blance']);
$sql = "INSERT INTO user (username, blance) VALUES ('$username',
'$blance')";
if ($con->query($sql) === TRUE) {
echo "success";
} else {
echo "error" . $sql . "<br>" . $con->error;
}
$sql6 = "SELECT * FROM user";
$result = mysqli_query($con, $sql6);
$resultcheck = mysqli_num_rows($result);
if ($resultcheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . "<br>";
}
}
echo "<br>" . "<br>" . "<br>";
}}
?>
</body>
This query will return sum of points for each username, assuming your table is named test
SELECT SUM(points) AS total_points
FROM test
GROUP BY username

Input from datepicker breaks inputs from dropdown lists

I created a filter for a table, which worked just fine at first, but as soon as I replaced the input form of the date with a datepicker I noticed that only the filter that involves the date works and the other are ignored and I can't see any reason why it behaves like this.
This is the part that creates the dropdown lists for the filter options:
echo "<form action='listTimes.php' method='post'>
<table>
<caption><b>Filter By:</b></caption>
<tr>
<th>Task Name</th>
<th>Task Stage</th>
<th>Name</th>
<th>Date</th>
</tr>
<tr>
<td>";
// first filter option - dropdown
$sql = "SELECT DISTINCT taskName FROM tasks";
$result = mysqli_query($link, $sql);
echo "<select name='taskName'>";
echo "<option selected='selected' value='' disabled='disabled'></option>";
while ($row = mysqli_fetch_array($result)) {
if (isset($row['taskName'])) {
echo "<option value='" . $row['taskName'] . "'>" . $row['taskName'] . "</option>";
}
}
echo "</select>
</td>
<td>";
// second filter option - dropdown
$sql = "SELECT DISTINCT taskStage FROM taskattributes";
$result = mysqli_query($link, $sql);
echo "<select name='taskStage'>
<option selected='selected' value='' disabled='disabled'></option>";
while ($row = mysqli_fetch_array($result)) {
if (isset($row['taskStage'])) {
echo "<option value='" . $row['taskStage'] . "'>" . $row['taskStage'] . "</option>";
}
}
echo "</select>
</td>
<td>";
// third filter option - dropdown
$sql = "SELECT DISTINCT userName FROM users";
$result = mysqli_query($link, $sql);
echo "<select name='userName'>";
echo "<option selected='selected' value='' disabled='disabled'></option>";
while ($row = mysqli_fetch_array($result)) {
if (isset($row['userName'])) {
echo "<option value='" . $row['userName'] . "'>" . $row['userName'] . "</option>";
}
}
/* fourth filter option, was just a simple text input at first. Now I changed it to a datepicker, which works, but the other three filter options stopped working at this point */
echo "</select>
</td>
<td>
<input type='text' class='datepicker' name='entryDate'>
</td>
</tr>
</table>
<div align='center'> <input type='submit' value='Filter'></div>
</form>
The filter mechanism behind is very poorly written, but works just fine:
if(!isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
{
$sql = "SELECT * FROM timeEntry";
$result = $link->query($sql);
}
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
{
$taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
$sql = "SELECT * FROM timeEntry WHERE taskName='$taskName'";
$result = $link->query($sql);
}
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
{
$taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
$taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
$sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage'";
$result = $link->query($sql);
}
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
{
$taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
$taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
$userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
$sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage' AND userName='$userName'";
$result = $link->query($sql);
}
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
{
$taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
$taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
$userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
$entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
$sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage' AND userName='$userName' AND entryDate='$entryDate'";
$result = $link->query($sql);
}
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
{
$taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
$userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
$entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
$sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage' AND userName='$userName' AND entryDate='$entryDate'";
$result = $link->query($sql);
}
elseif (!isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
{
$userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
$entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
$sql = "SELECT * FROM timeEntry WHERE userName='$userName' AND entryDate='$entryDate'";
$result = $link->query($sql);
}
elseif (!isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
{
$entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
$sql = "SELECT * FROM timeEntry WHERE entryDate='$entryDate'";
$result = $link->query($sql);
}
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
{
$taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
$entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
$sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage'AND entryDate='$entryDate'";
$result = $link->query($sql);
}
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && !isset($_POST['entryDate']))
{
$taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
$userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
$sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND userName='$userName'";
$result = $link->query($sql);
}
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && isset($_POST['entryDate']))
{
$taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
$userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
$entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
$sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND userName='$userName' AND entryDate='$entryDate'";
$result = $link->query($sql);
}
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && !isset($_POST['entryDate']))
{
$taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
$sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage'";
$result = $link->query($sql);
}
elseif (isset($_POST['taskName']) && isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
{
$taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
$taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
$entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
$sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND taskStage='$taskStage' AND entryDate='$entryDate'";
$result = $link->query($sql);
}
elseif (!isset($_POST['taskName']) && !isset($_POST['taskStage']) && isset($_POST['userName']) && !isset($_POST['entryDate']))
{
$userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
$sql = "SELECT * FROM timeEntry WHERE userName='$userName'";
$result = $link->query($sql);
}
elseif (isset($_POST['taskName']) && !isset($_POST['taskStage']) && !isset($_POST['userName']) && isset($_POST['entryDate']))
{
$taskName = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskName']));
$entryDate = mysqli_real_escape_string($link, htmlspecialchars($_POST['entryDate']));
$sql = "SELECT * FROM timeEntry WHERE taskName='$taskName' AND entryDate='$entryDate'";
$result = $link->query($sql);
}
elseif (!isset($_POST['taskName']) && isset($_POST['taskStage']) && isset($_POST['userName']) && !isset($_POST['entryDate']))
{
$taskStage = mysqli_real_escape_string($link, htmlspecialchars($_POST['taskStage']));
$userName = mysqli_real_escape_string($link, htmlspecialchars($_POST['userName']));
$sql = "SELECT * FROM timeEntry WHERE taskStage='$taskStage' AND userName='$userName'";
$result = $link->query($sql);
}
echo "<table class='top1' border='1'>
<tr>
<th>Entry No.</th>
<th>Task/Activity</th>
<th>Task Stage</th>
<th>User Name</th>
<th>Time Spent</th>
<th>Date</th>
<th>Edit Entry</th>
<th>Delete Entry</th>
</tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td align='center'>" . $row['timeId'] . "
</td>";
echo "<td>" . $row['taskName'] . "</td>";
echo "<td>" . $row['taskStage'] . "</td>";
echo "<td>" . $row['userName'] . "</td>";
echo "<td align='center'>" . $row['timeSpent'] . "</td>";
$originaldate = mysqli_real_escape_string($link, $row['entryDate']);
$newdate = date("d/m/Y", strtotime($row['entryDate']));
echo "<td align='center'>" . $newdate . "</td>";
echo "<td align='center'><a href='editAllTimes.php?timeId=" . $row["timeId"] . "'>Edit</a></td>";
echo "<td align='center'><a href='deleteAllTime.php?timeId=" . $row["timeId"] . "' onclick='return checkDelete()'>Delete</a></td>
</tr>";
}
echo "</table>";
}
This piece of code as bad as it looks, worked just fine before adding the date picker:
<input type='text' class='datepicker' name='entryDate'>
I have noticed a strange behavior:
If I delete the name attribute name='entryDate' the other filters work and the datepicker also, but the date is not recorded when I press filter and in consequence the date filter doesn't work.
If I leave the name attribute name='entryDate', the other three filters stop working, and only the date filter works.
Is there any reason for this behaviour? and any solution ?
I think the <input> element's values are always shown in $_POST despite of filled or not. You should try isset() and empty() check on the field.

isset($_POST['remember']) checkbox issue in PHP

I need to test if a checkbox is checked. I've searched for the solution and found it, but it still don't work for me.
Here's my form :
<form method="post" class="form-horizontal" role="form">
<div class="input-group">
<div class="checkbox">
<label>
<input id="remember" type="checkbox" name="remember" value="1"> Remember me
</label>
</div>
</div>
<div style="margin-top:10px" class="form-group">
<div class="col-sm-12 controls">
<button type="submit" class="btn btn-success" name="loginform">Login</button>
</div>
</div>
</form>
and my PHP code :
if (isset($_POST["loginform"])) {
if(isset($_POST['remember'])) {
$month = time() + 2592000;
debug_to_console($month); // function equivalent to console.log in JS
setcookie('remember_me', $_POST['username'], $month);
}
}
EDIT , debug_to_console() function :
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
EDIT 2 (Whole PHP code) :
<?php
session_start();
if(isset($_COOKIE['remember_me']))
$_SESSION['user'] = $_COOKIE['remember_me'];
$success = true;
if (isset($_POST["loginform"])) {
if(isset($_POST['remember'])) {
$month = time() + 2592000;
echo "<h1>Month: $month</h1>";
setcookie('remember_me', $_POST['username'], $month);
}
$password = $_POST['password'];
$email = $_POST['email'];
// Form Validation
if (!$email || !$password || !filter_var($email, FILTER_VALIDATE_EMAIL))
$success = false;
else
{
Db_connect($connection);
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysqli_real_escape_string($connection, $email);
$password = mysqli_real_escape_string($connection, $password);
$query = mysqli_query($connection, "select * from users where email='$email'");
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$row = mysqli_fetch_array($query);
$hashpass = $row['password'];
if ( hash_equals($hashpass, crypt($password, $hashpass)) ) {
$_SESSION['user'] = $row['username'];
header("location: login.php");
}
else
$success = false;
} else
$success = false;
mysqli_close($connection);
}
}
function Db_connect(&$connection){
$connection = mysqli_connect("localhost","root","", "project_web");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
?>
When i submit my form with the checkbox checked, and i look at the console, it is empty, while it is supposed to display the value of $month. Which means $_POST['remember'] is not set while it is supposed to be set due to the form submit.
Can anyone help please ?
Thank's in advance.
$_POST['remember'] would be true or false .... remove value =1 ... you will get value ... true or false ... validate according to that ...
Make an action attribute like
<form method="post" action="" class="form-horizontal" role="form">
The php code
if (isset($_POST)) {
if(isset($_POST['remember'])) {
$month = time() + 2592000;
debug_to_console($month); // function equivalent to console.log in JS
setcookie('remember_me', $_POST['username'], $month);
}
}

php - MYSQL Update Query not work complete

I have a little Problem with my Update query to chnage the Profile Infos
Problem now:
My Update Query is not working completly, the E-Mail query work but the status query is not working.
PHP CODE
if(!empty($_POST)) {
$query = "UPDATE users SET";
if(!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['email'] != $_SESSION['u']['email']) {
$s_mail = $_POST['email'];
$row = mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$s_mail'"));
if($row != 0) {
header("Location: ".$l['settings']."?msg=2");
die("REDIRECT");
}
$query .= " `email`='".$_POST['email']."'";
$_SESSION['u']['email'] = $_POST['email'];
} else if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
header("Location: ".$l['settings']."?msg=3");
die("REDIRECT");
}
//PROBLEM starts here
if(!empty($_POST['status'])) {
$query .= ",`status`='".$_POST['status']."'";
$_SESSION['u']['status'] = $_POST['status'];
}
//AND ends here
$query .= " WHERE id='".$_SESSION['u']['id']."'";
mysql_query($query);
header("Location: ".$l['settings']."?msg=1");
die("REDIRECT");
}
HTML FORM
<input maxlength="200" type="text" class="form-control" placeholder="Status" name="status" value="<?php //ECHO STATUS ?>" />
Maybe someone can help me.
On your $query you have
$query .= ",`status`='".$_POST['status']."'";
remove comma make it like this
$query .= " `status`='".$_POST['status']."'";
You need to set a flag for email condition as
$flag = FALSE;// set a flag
if (!empty($_POST)) {
if (!empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && $_POST['email'] != $_SESSION['u']['email']) {
$s_mail = $_POST['email'];
$row = mysql_num_rows(mysql_query("SELECT email FROM users WHERE email='$s_mail'"));
if ($row != 0) {
header("Location: " . $l['settings'] . "?msg=2");
die("REDIRECT");
}
$flag = TRUE;// set to true if success
$_SESSION['u']['email'] = $_POST['email'];
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
header("Location: " . $l['settings'] . "?msg=3");
die("REDIRECT");
}
//PROBLEM starts here
if (!empty($_POST['status'])) {
$query = "UPDATE users SET";
$query .= " `status`='" . $_POST['status'] . "'";
if ($flag) {// if true then apply email condition
$query .= ",`email`='" . $_POST['email'] . "'";
}
$query .= " WHERE id='" . $_SESSION['u']['id'] . "'";
$_SESSION['u']['status'] = $_POST['status'];
}
//AND ends here
mysql_query($query);
header("Location: " . $l['settings'] . "?msg=1");
die("REDIRECT");
}
Note:- mysql is deprecated instead use mysqli OR pdo

checking to see if a text box is empty in php

I have a php/html from where the user enters a number of values which are then updated into a database by using mysqli and a insert query, If the user does not enter anything into any of the text boxes I want a message to appear saying that the information is not there, I have tried using
if($ownerName == "" ){
echo("Missing Information!");
but it won't work.
Here is my php code
<?php
include "connect.php";
if($_POST["submit"])
{
$ownerName = $_POST['OwnerName'];
$location = $_POST['Location'];
$phoneNumber = $_POST['PhoneNumber'];
if($ownerName == "" || $location == "" || $phoneNumber == ""){
echo("Missing Information!");
/*if(is_numeric($phoneNumber) ){
settype($phoneNumber, "integer");
}*/
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}
?>
Here is my form
<html><head><title>Connect to Database</title></head><body>
<font size="4"> Enter owner details</font><br><br>
<form action="update.php" method="post" >
Owner Name:<input type="text" name="OwnerName">
Location: <input type="text" name="Location">
Phone Number:<input type="text" name="PhoneNumber">
<input type="submit" name = "submit" value="Submit Value">
</form></body></html>
try this:
if((!isset($ownerName)) || $ownerName == "" || (!isset($location)) || $location == "" || (!isset($phoneNumber)) || $phoneNumber == "")){
echo("Missing Information!");
/*if(is_numeric($phoneNumber) ){
settype($phoneNumber, "integer");
}*/
}
else{
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}
Try this
Change your condtion from
if($ownerName == "" || $location == "" || $phoneNumber == ""){
echo("Missing Information!");
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}
to
if($ownerName == "" || $location == "" || $phoneNumber == ""){
echo("Missing Information!");
} else {
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}
<?php
include "connect.php";
if(isset($_POST["submit"]))
{
$ownerName = isset($_POST['OwnerName']) ? $_POST['OwnerName']: '';
$location = isset($_POST['Location']) ? $_POST['Location']: '';
$phoneNumber = isset($_POST['PhoneNumber']) ? $_POST['PhoneNumber']: '';
//preventing sql injection
/*
$ownerName = mysqli_real_escape_string($con, $ownerName);
$$location = mysqli_real_escape_string($con, $ownerName);
$$phoneNumber = mysqli_real_escape_string($con, $ownerName);
*/
if(empty($ownerName) || empty($location) || empty($phoneNumber)){
echo("Missing Information!");
/*if(is_numeric($phoneNumber) ){
settype($phoneNumber, "integer");
}*/
}else{
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
}
mysqli_close($con);
?>
Also try using var_dump($_POST) to see what is sent.
EDIT:
I've updated if/else statement so now it should work. Also, make sure you have your error reporting enabled:
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
Try this
<?php
include "connect.php";
if($_POST["submit"])
{
$ownerName = $_POST['OwnerName'];
$location = $_POST['Location'];
$phoneNumber = $_POST['PhoneNumber'];}
if(empty($ownerName) && empty($location) && empty($phoneNumber))
{
echo("Missing Information!");}
/*if(is_numeric($phoneNumber) ){
settype($phoneNumber, "integer");
}*/
else{
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}
?>
Try this:
<?php
include "connect.php";
if($_POST["submit"])
{
$ownerName = $_POST['OwnerName'];
$location = $_POST['Location'];
$phoneNumber = $_POST['PhoneNumber'];
if($ownerName == "" || $location == "" || $phoneNumber == ""){
echo("Missing Information!");
}
else{
$query = "INSERT INTO OWNER VALUES ('$ownerName','$location', $phoneNumber)";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
}
mysqli_close($con);
}
?>
**Please replace your code from below code**
<?php
include "connect.php";
if($_POST["submit"])
{
$ownerName = $_POST['OwnerName'];
$location = $_POST['Location'];
$phoneNumber = $_POST['PhoneNumber'];
if($ownerName == "" || $location == "" || $phoneNumber == ""){
echo("Missing Information!");
} else {
// please replace your column name (`owner_name`, `location`, `phone_number`)
$query = "INSERT INTO OWNER (`owner_name`, `location`, `phone`) VALUES ('" . $ownerName . "', '" . $location. "', " . $phoneNumber. ")";
if (!mysqli_query($con, $query))
{
die('Error: ' . mysqli_error($con));
}
echo "<script type='text/javascript'>alert('1 record added')</script>";
mysqli_close($con);
}
}
?>
Try to use empty() function or isset()

Categories