PhP & MySQL WHERE Syntax - php

There is a registration interface where you must enter your billing information after logging in.
The goal is to record the entered data in the MySQL database and update the "billable" value to "1", however I get a syntax error.
The code is (PhP 7.3):
<?php
session_start();
if(!isset($_SESSION['username'])) {
header('location: login.php');
exit();
}
include_once('dbconnect.php');
$username = $_SESSION["username"];
$result = mysqli_query($conn, "SELECT * FROM users WHERE username = '$username'");
while($row = mysqli_fetch_array($result)) {
if ($row['billable'] == 0) {
$error = false;
if(isset($_POST['btn-updatedetails'])) {
$firstname = mysqli_real_escape_string($conn, $_REQUEST['firstname']);
$lastname = mysqli_real_escape_string($conn, $_REQUEST['lastname']);
$phone = mysqli_real_escape_string($conn, $_REQUEST['phone']);
$company = mysqli_real_escape_string($conn, $_REQUEST['company']);
$country = mysqli_real_escape_string($conn, $_REQUEST['country']);
$county = mysqli_real_escape_string($conn, $_REQUEST['county']);
$city = mysqli_real_escape_string($conn, $_REQUEST['city']);
$street = mysqli_real_escape_string($conn, $_REQUEST['street']);
$postcode = mysqli_real_escape_string($conn, $_REQUEST['postcode']);
if(empty($firstname)) {
$error = true;
$errorFirstname = 'This field cannot be left blank.';
}
if(empty($lastname)) {
$error = true;
$errorLastname = 'This field cannot be left blank.';
}
if(empty($phone)) {
$error = true;
$errorPhone = 'This field cannot be left blank.';
}
if(empty($country)) {
$error = true;
$errorCountry = 'This field cannot be left blank.';
}
if(empty($county)) {
$error = true;
$errorCounty = 'This field cannot be left blank.';
}
if(empty($city)) {
$error = true;
$errorCity = 'This field cannot be left blank.';
}
if(empty($street)) {
$error = true;
$errorStreet = 'This field cannot be left blank.';
}
if(empty($postcode)) {
$error = true;
$errorPostcode = 'This field cannot be left blank.';
}
if(!$error){
$sql = "INSERT INTO users (firstname, lastname, phone, company, country, county, city, street, postcode) VALUES ('$firstname', '$lastname', '$phone', '$company', '$country', '$county', '$city', '$street', '$postcode') WHERE username = '$username' AND UPDATE users SET billable='1' WHERE username = '$username'";
if(mysqli_query($conn, $sql)){
$successMsg = 'Success!';
}else{
echo 'Error '.mysqli_error($conn);
}
}
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
Firstname:
<input type="text" name="firstname" id="firstname"><br>
Lastname:
<input type="text" name="lastname" id="lastname"><br>
Phone:
<input type="text" name="phone" id="phone"><br>
Company (optional):
<input type="text" name="company" id="company"><br>
Country:
<input type="text" name="country" id="country"><br>
County:
<input type="text" name="county" id="county"><br>
City:
<input type="text" name="city" id="city"><br>
Street:
<input type="text" name="street" id="street"><br>
Postcode:
<input type="text" name="postcode" id="postcode"><br>
<input type="submit" name="btn-updatedetails">
</form>
<?php
} else {
echo "<3";
}
}
mysqli_close($conn);
This page returns the following error:
Error You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE username = 'Erik' AND UPDATE users SET billable='1' WHERE username = 'Erik' at line 1
MySQL database:
Where did I make a mistake?
Thank you in advance for your answer!
Have a nice day!

You did a SELECT to start with so I don't see why you want to INSERT another row for the same user. I think you just want to do a single UPDATE as such:
UPDATE users
SET
firstname = '$firstname',
lastname = '$lastname',
phone = '$phone',
company = '$company',
country = '$country',
county = '$county',
city = '$city',
street = '$street',
postcode = '$postcode',
billable = 1
WHERE username = '$username'

Related

MySQL database could not be updated with PHP program

addmember.php
<?php
require_once("dbtools.inc.php");
$account = $_POST["account"];
$password = $_POST["password"];
$name = $_POST["name"];
$sex = $_POST["sex"];
$year = $_POST["year"];
$month = $_POST["month"];
$day = $_POST["day"];
$telephone = $_POST["telephone"];
$address = $_POST["address"];
$email = $_POST["email"];
$comment = $_POST["comment"];
$link = create_connection();
$sql = "SELECT * FROM users Where account = '$account'";
$result = execute_sql($link, "member", $sql);
if (mysqli_num_rows($result) != 0)
{
mysqli_free_result($result);
echo "<script type='text/javascript'>";
echo "alert('Account already in use! Please choose another username');";
echo "history.back();";
echo "</script>";
}
else
{
mysqli_free_result($result);
$sql = "INSERT INTO users (account, password, name, sex,
year, month, day, telephone, address,
email, comment) VALUES ('$account', '$password',
'$name', '$sex', $year, $month, $day, '$telephone',
'$address', '$email', '$comment')";
$result = execute_sql($link, "member", $sql);
echo "User added successfully!";
}
mysqli_close($link);
?>
join.html
<form action="addmember.php" method="POST" name="myForm">
(Different types of input)
<input type="submit" value="Add">
My aim is to add a member data into the database after the user clicked the Add button on the form in join.html. However the page could run echo "User added successfully!"; this line but the problem is the database could not get updated even though I already called execute_sql command. May I ask what is missing in order to be connected with the database?

How to avoid duplicate emails php / sql?

I used this code and I don't know what is the problem and I used different codes as well
what I want to do to check and not allow the user to add his email twice
<?php
include("includedb.php");
//declare variables
$name = $_POST['name'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$gift = $_POST['gift'];
$formName = $_POST['formName'];
$formEmail = $_POST['formEmail'];
$formEmirate = $_POST['formEmirate'];
$birthday = $_POST['birthday'];
$date = $_POST['date'];
$result = mysqli_query("SELECT * FROM users WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates
$num_rows = mysqli_num_rows($result); //number of rows where duplicates exist
if ($num_rows == 0) { //if there are no duplicates...insert
$sql = "INSERT INTO users (name, email, tel, gift, formName, formEmail, formEmirate, birthday, date)
VALUES ('$name', '$email', '$tel','$gift', '$formName', '$formEmail', '$formEmirate','$birthday',CURRENT_TIMESTAMP )";
if (!mysqli_query($sql)) {
die('Error: ' . mysqli_error());
}
}
mysqli_close();
header("location: thank-you.html?remarks=success");
?>
the problem is you are not passing any connection to the mysql_query
thus the queries are not getting queried
$conn = your connection;
$result = mysqli_query($conn,"SELECT * FROM users WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates
$num_rows = mysqli_num_rows($result); //number of rows where duplicates exist
if($num_rows == 0) { //if there are no duplicates...insert
$sql = "INSERT INTO users (name, email, tel, gift, formName, formEmail, formEmirate, birthday, date)
VALUES ('$name', '$email', '$tel','$gift', '$formName', '$formEmail', '$formEmirate','$birthday',CURRENT_TIMESTAMP )";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error());
}
}
thanks for support I found what has worked with me please find the code below and please advise me how to make it secure and protect it from sql injection
if(isset($_POST['submit'])){
$name= $_POST['name'];
$email= $_POST['email'];
$result = mysqli_query($conn,"SELECT * FROM test WHERE email = '$email'") or exit(mysqli_error()); //check for duplicates
$num_rows = mysqli_num_rows($result); //number of rows where duplicates exist
if(($num_rows) > 0){
echo "A record already exists.";
exit;
}
else{
$sql = "INSERT INTO test (name, email)
VALUES ('$name', '$email')";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error());
}
}
if($result) {
header("Location: game.html");
}else{ echo "Not Successful"; }
mysqli_close();
}
?>
<!DOCTYPE html>
<head>
</head>
<body>
<h2>Enter your Name and Email</h2>
<form method="post">
<p><strong>First Name:</strong><br /> <input type="text" name="name" /></p>
<p><strong>email:</strong><br /> <input type="email" name="email"/></p>
<input type="submit" name="submit" value="Add Customer" />
</form>
</body>
</html>

Information not getting submitted to MySQL

I am creating a simple login script using PHP and MySQL, no errors are coming up but for some reason the information submitted is just not being inserted into the database.
The database is named 'test' (Without quotes) and the table 'users' (Also without quotes).
The columns in the table are first_name, last_name, email, pass and registration_date.
Here is the html form:
<form action="script4.php" method="post">
<p>First Name:<input type="text" name="first_name" value="first_name" /></p>
<p>Last Name:<input type="text" name="last_name" value="last_name" /></p>
<p>Email: <input type="text" name="email" value="email" /></p>
<p>Password: <input type="password" name="pass1" value="pass1" /></p>
<p>Confirm Password: <input type="password" name="pass2" value="pass2"/></p>
<input type="submit" name="submit" value="register" />
</form>
and here is script4.php
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
require ('mysql_connect.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();}
if (!empty($_POST['first_name'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$fn = trim($_POST['first_name']);
}
if (!empty($_POST['last_name'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$ln = trim($_POST['last_name']);
}
if (!empty($_POST['email'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$e = trim($_POST['email']);
}
if (!empty($_POST['pass1'])) {
if ($_POST['pass1'] != $_POST['pass2']) {
$errors[] = "Your passwords do not match.";
} else {
$p = trim($_POST['pass1']);}
}else {
$errors[] = "You forgot to enter your password.";
}
if (empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO users ('first_name', 'last_name', 'email', 'pass', 'registration_date') VALUES ('$first_name', '$last_name', '$email', SHA1('$pass'), NOW()) or trigger_error('Query Error: ' . mysql_error());";
$r = #mysqli_query ($dbc, $q);
if ($r) {
echo("Thanks");
} else {
echo("We are sorry, you could not be entered at this time.");
echo mysqli_error($dbc);
} }
mysqli_close($dbc);
?>
I know this script is vulnerable to sql injection, it is just a test:)
The data will just not get submitted.
Remove the single quotes from the column names.
You are calling require ('mysql_connect.php') twice.
You had multiple syntax errors.
You were assigning variables but not calling them.
You tried to add $pass to the database instead of $pass1.
I cleaned your code.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
$first_name = empty($_POST['first_name']) ? '' : trim($_POST['first_name']);;
$last_name = empty($_POST['last_name']) ? '' : trim($_POST['last_name']);;
$email = empty($_POST['email']) ? '' : trim($_POST['email']);;
$pass1 = empty($_POST['pass1']) ? '' : trim($_POST['pass1']);
$pass2 = $_POST['pass2'];
if (!$first_name) {
$errors[] = "You forgot to enter your first name!";
}
if (!$last_name) {
$errors[] = "You forgot to enter your first name!";
}
if (!$email) {
$errors[] = "You forgot to enter your first name!";
}
if ($pass1) {
if ($pass1 != $pass2) {
$errors[] = "Your passwords do not match.";
}
} else {
$errors[] = "You forgot to enter your password.";
}
if (empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO users (first_name, last_name, email, pass,registration_date) VALUES ('$first_name', '$last_name', '$email', SHA1('$pass1'), NOW()) or trigger_error('Query Error: ' . mysql_error());";
$r = #mysqli_query ($dbc, $q);
if ($r) {
echo("Thanks");
} else {
echo("We are sorry, you could not be entered at this time.");
echo mysqli_error($dbc);
}
mysqli_close($dbc);
} else {
foreach ($errors as $error) echo $error . '<br>';
}
}
?>
Also, it will be wise to escape the $_POST data or even better - use a prepared statements as currently, you are volunerable to SQL injection.
Hope this helps!
Remove the ! in all your conditional statements:
if (!empty($_POST['last_name']))
Means "if last_name is NOT empty", because of the !. Which means that your script currently says "error" if the fields are NOT empty. And if the scripts says "error", then in the end it doesn't insert the values in the database.
It doesn't say "we are sorry" too, because this statement is inside your conditional if(empty($errors)). So if $errors is not empty, you directly go to the end of the script without displaying anything, but witout having inserted your values.
So what you should do, for instance, is this:
if (empty($_POST['first_name'])) {
$errors[] = "You forgot to enter your first name!";
} else {
$fn = trim($_POST['first_name']);
}
And in the end:
if (empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO users (first_name, last_name, email, pass, registration_date) VALUES ($first_name, $last_name, $email, SHA1($pass), NOW());";
if (#mysqli_query ($dbc, $q)) {
echo("Thanks");
} else {
echo mysqli_error($dbc);
echo("We are sorry, there is a problem with the database connection.");
}
} else {
echo("We are sorry, there are errors in the values you entered.");
}
mysqli_close($dbc);
As the others said, be careful because you have to remove one of your require('mysql_connect.php').
Remove the first require ('mysql_connect.php');
and change the following line to something like this because you got wrong syntax for your query and your trigger_error
$q = "INSERT INTO users (first_name, last_name, email, pass, registration_date) VALUES ('$first_name', '$last_name', '$email', SHA1('$pass'), NOW())";
$r = mysqli_query($dbc, $q) or trigger_error('Query Error: ' . mysqli_error($dbc));
Remove the # and change mysql_error to mysqli_error with link otherwise you won't get your error.
if(empty($errors)) {
require ('mysql_connect.php');
$q = "INSERT INTO `users` (`first_name`, `last_name`, `email`, `pass`, `registration_date`) VALUES ('$first_name', '$last_name', '$email', SHA1('$pass'), NOW())";
$r = mysqli_query ($dbc, $q);
if($r){
echo "Thanks";
}else{
echo "We are sorry, you could not be entered at this time.";
trigger_error('Query Error: ' . mysqli_error($dbc));
}
mysqli_close($dbc);
}
Also you should look into binding parameters so eliminate sql injections.

Insert form data into MySQL database

Hi Guys I am having a problem that when adding form data into a database. For some reason the data is not inserted. here is my code:
<?php include_once 'secure/connect.php'; ?>
<?php
$name = "Your Name";
$email = "Your Best Email";
$msg_to_user = "";
if ($_POST['name'] != ""){
//Be sure to filter this data to deter SQL injection
$name = $_POST['name'];
$name = stripslashes($name);
$name = strip_tags($name);
$email = $_POST['email'];
$email = stripslashes($email);
$email = strip_tags($email);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if(!$email){
$msg_to_user = '<h4><font color="FF0000">Please Type an email address ' . $name . '</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<h4><font color="FF0000">' . $email . ' is already in our system</font></h4>';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime) VALUES ('$name', '$email', now())") or die (mysql_error());
$msg_to_user = '<h4><font color="0066FF">Thanks' . $name . ', You have been added successfully</font></h4>';
$name = "";
$email = "";
}
}
?>
And my html form looks like this:
<div class="topForm">
<H3 style="text-align:center">SIGN UP FOR OUR NEWSLETTER</H3>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="name" value="<?php echo $name; ?>"/>
<input type="text" name="email" value="<?php echo $email; ?>"/><br/>
<input name="mySubmitBtn" type="submit" value="SUBMIT">
<?php echo $msg_to_user; ?>
</form>
</div>
Many thanks in advance all
Phillip
This is what I have now and nothing is still working...
<?php
$name = "Your Name";
$email = "Your Best Email";
$msg_to_user = "";
if ($_POST['name'] != ""){
include_once 'secure/connect.php';
//Be sure to filter this data to deter SQL injection
$name = $_POST['name'];
$name = stripslashes($name);
$name = strip_tags($name);
$email = $_POST['email'];
$email = stripslashes($email);
$email = strip_tags($email);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if(!$email){
$msg_to_user = '<h4><font color="FF0000">Please Type an email address ' . $name . '</font></h4>';
} else if ($numRows > 0) {
$msg_to_user = '<h4><font color="FF0000">' . $email . ' is already in our system</font></h4>';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email) VALUES ('".$name."', '".$email."')") or die (mysql_error());
$msg_to_user = '<h4><font color="0066FF">Thanks' . $name . ', You have been added successfully</font></h4>';
$name = "";
$email = "";
}
}
?>
without regard to other errors or inconsistencies. also let me note that you should use mysqli or pdo. but php uses time()
$sql_insert = mysql_query("
INSERT INTO newsletter
(name, email, dateTime)
VALUES
('$name', '$email', ".time().")
");
or if you want a date time instead of the timestamp you can use the date() function.
You have to change now() from your code. And Use Following code.
$time = time() ;
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime) VALUES ('".$name."', '".$email."', '".$time."' )") or die (mysql_error());
make sure you are connected to the database ! see what echo mysql_error(); says
if a form was submitted, catch the values, and then sanitize
insert query
ps: see what the following do:
if(isset($_POST['name']) ...
echo mysql_insert_id();
time() not now()
see the id of the new data inserted
your code, should work, if you follow these steps, and if you are connected to the database

Unknow php error in sql INSERT INTO

I have problem in my registration.
Look on my code:
//player.php
<?php
session_start();
class Player
{
var $name;
function _construct($name)
{
$this->$name = $name;
}
function CreatePlayer($name, $pass, $mail, $date, $type)
{
if($_POST['submit'])
{
$link = mysql_connect("localhost","wewewe", "wewewe");
if(!$con)
{
die( $return = mysql_error());
}
mysql_select_db("wewewe", $con);
mysql_query("INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')");
mysql_close(link);
}
return $return;
}
function LoginPlayer($name, $pass)
{
$link = mysql_connect("localhost","username", "pass");
mysql_select_db("con", $con);
$result = mysql_query("SELECT FROM USERS WHERE pass='$pass' AND name='$name'");
$count = mysql_num_rows($result);
if($count==1)
{
$_SESSION['name'] = $name;
$_SESSION['logged'] = true;
}
mysql_close($link);
}
}
?>
//reg.php
<html>
<form action="log.php" method="post">
Meno: <input type="text" name="meno">
<br>
Heslo: <input type="text" name="heslo">
<br>
Mail: <input type="text" name="mail">
<br>
Date: <input type="text" name="date">
<br>
Type: <input type="text" name="type">
<br>
<input type="submit">
<br>
</form>
<?php
include 'player.php';
$name = $_POST['meno'];
$pass = $_POST['heslo'];
$mail = $_POST['mail'];
$date = $_POST['date'];
$type = $_POST['type'];
$obj = new Player($name);
$res = $obj->CreatePlayer($name, $pass, $mail, $date, $type);
if($res==true)
{
echo "jo!";
}
else
{
echo $res;
}
?>
My problem is that if I write text to all fields and press ok, my page will restart but without any error message. And when I will look to a database, theres nothing. Why? Can anybody plese help me?
EDIT:
<?php
session_start();
class Player
{
var $name;
function _construct($name)
{
$this->$name = $name;
}
function CreatePlayer($name, $pass, $mail, $date, $type)
{
if($_POST['submit'])
{
$con = mysql_connect("localhost","wewewe", "wewewe");
if(!$con)
{
die( $return = mysql_error());
}
mysql_select_db("wewewe", $con);
$query = "INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')";
$retrn = var_dump($query); // SHOWS YOU QUERY STRING
mysql_query($query) or die(mysql_error()); // EXECUTES QUERY OR THROWS EXCEPTON (SHOWS ERROR TOO)
mysql_close($con);
}
return $return;
}
function LoginPlayer($name, $pass)
{
$link = mysql_connect("localhost","username", "pass");
mysql_select_db("con", $con);
$result = mysql_query("SELECT FROM USERS WHERE pass='$pass' AND name='$name'");
$count = mysql_num_rows($result);
if($count==1)
{
$_SESSION['name'] = $name;
$_SESSION['logged'] = true;
}
mysql_close($link);
}
}
?>
I think its not going inside if($_POST['submit'])
change
<input type="submit">
to
<input name="submit" type="submit" />
<input type="submit"> modify to <input type="submit" name="submit">
To debug SQL INSERTING :
mysql_select_db("wewewe", $con);
mysql_query("INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')");
mysql_close(link);
modify to
mysql_select_db("wewewe", $con);
$query = "INSERT INTO USERS (name, pass, mail, date, type) VALUES ('$name', '$pass', '$mail', '$date','$type')";
var_dump($query); // SHOWS YOU QUERY STRING
mysql_query($query) or die(mysql_error()); // EXECUTES QUERY OR THROWS EXCEPTON (SHOWS ERROR TOO)
mysql_close(link);
Your query in the function LoginPlayer is incorrect. You may simply fix it like this
$result = mysql_query("SELECT name FROM USERS WHERE pass='$pass' AND name='$name'");

Categories