php & mysql please select an other date- message is not appearing - php

I have two issues and both are linked. First, "already booked - please select another date" is not appearing, if two clients select the same product (pg_no) and date (Date). These fields are UNIQUE CONSTRAINT.
Second, when data is inserted or submitted localhost shows complete address
http://localhost/lstcomp/index.php?note=submitted. But when it fails the localhost shows only : http://localhost/lstcomp/
<?php
//connecting string
include("dbconnect.php");
//assigning
$name = $_REQUEST['Name'];
$tele = $_REQUEST['Tele'];
$city = $_REQUEST['City'];
// UNIQUE CONSTRAINT
$pg_no = $_REQUEST['pg_no']; //product
$date = $_REQUEST['Date']; //date
//checking if pg_no and Date are same
$check = mysqli_query($db_connect, "SELECT * FROM lstclient WHERE pg_no='{$pg_no}', Date='{$date}'");
{
echo "Already booked please select another date<br/>";
}
//if not same then insert data
else
{
$query = mysqli_query($db_connect, "INSERT INTO lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}
mysqli_close($db_connect);
// messaging
if ($query) {
header("location:index.php?note=failed");
} else {
header("location:index.php?note=success");
}
?>

There are a few problems:
The file fails to parse because of the dangling else; it's not paired with an if-statement.
{
echo "Already booked please select another date<br/>";
}
//if not same then insert data
else
{
$query = mysqli_query($db_connect, "INSERT INTO lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}
It looks like you're intending to use the result from your SELECT statement ($check), however...
The SELECT statement is invalid; WHERE clauses are separated with AND or OR, not commas.
When inserting the row into the database table, you're dying on mysql_error when you've been using the mysqli extension.
You're vulnerable to SQL injection attacks; if pg_no happened to be '; DELETE FROM users; --, as an example, your user table would be deleted. You're already using the mysqli extension, so use parameter binding and prepared statements. Reference

Related

Inserting data into Mysql with PHP while loop

I'm trying to check an email against my database, and if it doesn't already exist, add it to the database.
$query = "SELECT * FROM users";
$inputQuery = "INSERT INTO users (`email`,
`password`) VALUES ('$emailInput',
'$passInput')";
$emailInput = ($_POST['email']);
$passInput = ($_POST['password']);
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
if ($row['email'] == $emailInput) {
echo "We already have that email!";
} else {
mysqli_query($link, $inputQuery);
echo "Hopefully that's been added to the database!";
}
}
};
It can detect an existing email, it's just the adding bit...
Currently this seems to add a new empty row for each existing row (doubling the size).
I'm trying to understand why it doesn't add the information, and how to escape the loop somehow.
Also for good measure, everyone seems to reuse $query, but this seems odd to me. Is it good practice to individually name queries as I have here?
Please let me know if there's anything else I should add.
I am not going to talk about the standards but straight, simple answer to your question.
Approach - 1:
INSERT INTO users (`email`,`password`) SELECT '$emailInput', '$passInput' from DUAL WHERE NOT EXISTS (select * from users where `email` = '$emailInput');
Approach - 2:
- Create a unique key on email column
- use INSERT IGNORE option.
user3783243 comments are worth noting
Try this :
$emailInput = mysqli_real_escape_string($link, $_POST['email']);
$passInput = mysqli_real_escape_string($link, $_POST['password']);
$qry3=mysqli_query($link,"select * from users where `email`='".$emailInput."'");
$num=mysqli_num_rows($qry3);
if($num==1) {
echo "Email-Id already exists";
} else {
$inputQuery = mysqli_query($link,"INSERT INTO users (`email`, `password`) VALUES ('".$emailInput."', '".$passInput."')");
if ($inputQuery) {
echo "Hopefully that's been added to the database!";
}
}
Your code seems to be a bit over-engineered because why not to pass you $_POST['email'] to select query where clause
"SELECT * FROM users where email = $emailInput" and then check if it is there already.
Also, keep in mind that this is an example only, and you should always check and sanitize user input.
From another hand you can do it with MySQL only using INSERT ... ON DUPLICATE KEY UPDATE Syntax. https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
That requires to add unique key for email column.

Find a user using a form with PHP backend

I'm trying to check if a user exists on the database using a form front end.
If the user is there don't add to the database.
The code isn't working when adding a user it gives me the user has been added even the user exists.
Here my code:
<?php
$connection = mysql_connect("localhost", "dbuser", "dbpasswd"); // Establishing Connection with Server
$db = mysql_select_db("ldap", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$netid = $_POST['netid'];
$univid = $_POST['univid'];
if($netid !=''||$univid !=''){
//Insert Query of SQL
$query = mysql_query("SELECT FROM user ( UserName, temppass WHERE UserName=$netid");
if(mysql_num_rows($sql)>=1)
{
echo"NetID $netid already exists";
}
else
{
//insert query goes here
$query = mysql_query("insert into user( UserName, temppass ) values ('$netid', '$univid')");
}
echo "<br/><br/><span>User Registered successfully...!!</span>";
}
else{
echo "<p>Registration Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
?>
You could do something like:
$query = mysql_query("SELECT COUNT(UserName) as total FROM user;");
Then
$result = mysql_fetch_assoc($query);
The count of users will be in $result['total']. As an aside the mysql_* methods are inferior to prepared statements (google it).
Your select query has many errors with it.
SELECT FROM user ( UserName, temppass WHERE UserName=$netid
First issue you aren't selecting anything. Second issue I don't know what ( UserName, temppass is, maybe the columns you want to select? Third issue is that Username is presumably a string, not an integer, so that value should be in quotes. Once you quote that though you will open yourself to SQL injections.
Here is a valid version of your current query.
SELECT UserName, temppass FROM user WHERE UserName='$netid'
Here's the doc on mysql's select: http://dev.mysql.com/doc/refman/5.7/en/select.html
Here are some links to read up on about SQL injections:
How can I prevent SQL injection in PHP?http://php.net/manual/en/security.database.sql-injection.php
You also shouldn't be using the mysql_ functions they are deprecated and insecure now. Why shouldn't I use mysql_* functions in PHP?
Additional issues:
if(mysql_num_rows($sql)>=1)
The $sql isn't defined.
I don't know what $_POST['netid'] is but that sounds like an id, not a username.
You shouldn't store passwords in plain text.
You should enable error reporting and/or monitor your error logs.

select a value from a table with the help of php variable

I am using a variable in my php code named $user_id. This variable takes a value after executing a short script of code. I also have a table named users in my database and this table holds user_id and email. If want to select email from my database, when the user_id from my table is equal to my variable named $user_id. Can I do this? This is my query:
<?php
//code ...
$user_id=$_GET['user']; //$user_id gets a value here
//now I want to select email from table users, where user_id is equal to variable $user_id
mysql_query(" SELECT `email` FROM `users` WHERE `user_id`='$user_id' ");
?>
Yes, it will work. I'd though advise you to use pdo or mysqli instead of mysql_* functions. They have been deprecated.
If for some reasons you can not switch to either of them; you should filter/sanitize your query.
Also, if user_id is a numeric field, you wouldn't be needing to enclose $user_id in quotes.
Your code has the basics, it just needs handling and I would add a couple of checks.
if(isset($_GET["user"]) && $_GET["user"] != "") //check there is a value for the user ID
{
if(is_int($_GET["user"]))
{
$user_id=$_GET["user"]);
$email="";
$q=mysql_query("SELECT email FROM users WHERE user_id={$user_id}") or die(mysql_error());
if(mysql_num_rows($q) > 0)
{
while($user=mysql_fetch_assoc($q))
{
$email=$user["email"];
}
}
else
{
echo "no users found";
}
}
else
{
echo "Not a valid user ID, please enter numeric value";
}
}
else
{
echo "No UserID";
}
hjpotter92 recommends that you use mysqli or pdo for questioning your database, which I would agree with although while learning keep with mysql as there are more resources available for learning, then when confident move onto newer technologies.
Please note: I have based this on the experience I feel the user has got with PHP and MySQL not on the most modern or best practices.
The code should be:
$email = '';
$res = mysqli_query(" SELECT `email` FROM `users` WHERE `user_id`='$user_id' ");
while ($temp = mysqli_fetch_assoc($res)) {
$email = $temp['email'];
}

Check if mysql entry exits then DELETE

I'm kind of a stuck in searching for a solution.
I need to check if an input data $coupon from the form (after "post" action) equals data in the existing MySQL table called Serial, in the row $Coupon. If those two entries match i need the one in table "Serial" removed (DELETED From). In the other case I need to display an Error, maybe like echo "The coupon number you've entered is invalid".
Now i have the following code, but it doesnt do the check.
$query4="SELECT EXISTS(SELECT 1 FROM serial WHERE Coupon='$coupon')";
$result = mysql_query($query4);
if($result){
echo "Bravo!";
}
else{
"The coupon number you've entered is invalid";
exit;
}
// Delete data from mysql
$query2="DELETE FROM serial WHERE Coupon = '$coupon'";
$result = mysql_query($query2);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Some info";
}
else {
die(mysql_error());
}
Appreciate any ideas greatly!
You've created a race condition for yourself. The fact that the coupon exists when you run the SELECT statement does not mean that it will exist when you run the delete statement, especially if this is a web app, or multi-threaded/multi-process.
The DELETE statement deletes rows from tbl_name and returns a count of the number of deleted rows. This count can be obtained by calling the ROW_COUNT() function.
Run your DELETE unconditionally, then use the ROW_COUNT to see if it was there and got deleted or wasn't ever there.
First of all phase out mysql_* functionality or you have bigger problems than checking the result. Your code is vulnerable to SQL Injection. Use PDO or MySQLi instead.
Secondly, why do you need EXISTS in the first query at all?
Here is the solution in PDO:
$query = 'SELECT 1 FROM serial WHERE Coupon = :coupon';
$stmt = PDO->prepare($query);
$stmt->bindParam(':coupon', $coupon, DB::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() > 0) {
//query 2
$query2 = "DELETE FROM serial WHERE Coupon = :coupon";
$stmt2 = PDO->prepare($query2);
$stmt2->bindParam(':coupon', $coupon, DB::PARAM_STR);
if ($stmt2->execute()) {
echo 'Success';
} else {
echo 'Unable to Delete';
}
} else {
echo 'Selected Coupon Is Invalid';
}
OR MORE SIMPLY IN ONE QUERY:
$query = 'DELETE FROM serial WHERE coupon = :coupon';
$stmt = PDO->prepare($query);
$stmt->bindParam(':coupon', $coupon, DB::PARAM_STR);
if ($stmt->execute()) {
echo 'Success';
} else {
echo 'failure, invalid coupon';
}
You can actually just do SELECT 1 FROM serial...
Then:
$result = mysql_query($query4);
if (mysql_num_rows($result)) {
If it returns a row, you know it exists. You can also add LIMIT 1 to the query to make it faster.
By the way, your code is vulnerable to injection. You should use properly parameterized queries with PDO or mysqli.
Following up from mluebke's answer:
// Delete data from mysql
$query="DELETE FROM serial WHERE Coupon = '$coupon'";
mysql_query($query);
//Did we delete something?
if (mysql_affected_rows()) {
echo "Bravo!";
}
else{
"The coupon number you've entered is invalid";
exit;
}
http://www.php.net/manual/en/function.mysql-affected-rows.php
http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_row-count

INSERT INTO table1 values FROM table2 WHERE

I've looked around nothing seems to be working for me. I have a button when pushed it INSERTS data into 1 table-1, then it gets values from table-3 to put in table-2 where in they the ID is the same.
if ($movieTime != "") {
$query = "SELECT SchedID FROM tblCinemaSched WHERE TheaterID='$tid' AND CinemaID='$cid' AND MovieDate='$date' AND MovieTime='$movieTime'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$numRows=$conn->numRows($result);
if ($numRows<=0) {
$query = "INSERT INTO tblCinemaSched SET TheaterID='$tid', CinemaID='$cid', MovieDate='$date', MovieTime='$movieTime', MovieID='$movieId', PriceAmt='$priceId', CrtBy='$username', CrtDate=NOW()";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
//get seat defaults from tblCSeats
$query = "INSERT INTO tblSSeats SELECT TheaterID, CinemaID, '$date', '$movieTime', SeatID, RowNo, ColumnNo, Handicap, Status, LeftSeat, RightSeat, NULL, NULL,NULL,NULL,NULL,NULL,NULL,'$username',NOW() FROM tblCSeats WHERE TheaterID='$tid' AND CinemaID='$cid'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$errorStr = "Succesfully added schedule.";
}
else {
$errorStr = "There's already an existing schedule for the specified time.";
}
You see tableCSeats has more than 1 row that has the same ID meaning I want to insert multiple data from tableCSeats to tableSSeats. tableSSeats is a has no data in it yet.
At a blind guess, it would seem that you are looking for INSERT ... SELECT statement.
check the return values of your queries. You always get "Succesfully added schedule." because you don't check if the queries were succesful. Ex:
if(!$result=$conn->executeUpdate($query)) {
die('error');
}
or something like that.

Categories