Getting an error of SQl Syntax - php

Getting an error of
"Error: 1
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 '1' at line 1"
Please help guys, Many thanks in advance.
Code:
<?php
include('head.php');
if(isset($_POST['submit']))
{
$userid = trim($_POST['userid']);
$email = trim($_POST['email']);
$mobile = trim($_POST['mobile']);
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>******</title>
<link href="forum-styles.css" rel="stylesheet" type="text/css">
</head>
<style type="text/css">
.txtField {
padding: 5px;
border:#fedc4d 1px solid;
border-radius:4px;
}
</style>
<body background="img/gold-and-money.jpg">
<form action="" method="post" class="basic-grey">
<h1>****** Forgot Password
<span>Please let us know your UserId, We will reset password and inform you.</span> </h1>
<label>
<span>User Id :</span>
<input type="text" name="userid" required />
</label>
<label>
<span>Mobile N. :</span>
<input type="text" name="mobile" required/>
</label>
<label>
<span>Email Id :</span>
<input type="text" name="email" required/>
</label>
<label>
<div align="right"><span> </span>
<input type="submit" class="button" value="Submit" name="submit"/>
</div>
</label>
</form>
</body>
</html>

$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You've got two calls here to mysqli_query. The first time, you're making the query and assigning the return value to $sql; the second time, you're running $sql as a query.
To fix the immediate problem, do something along the lines of:
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You're assigning your query to a string, and then using that in your query. This makes debugging things easier, as you can now output your generated query to check what you're producing.
However
You're also passing user-generated data directly into an SQL query, without escaping it. This is very bad - at best, you're going to have a problem if some of the data contains apostrophes. At worst, your database will get hacked. One solution here is to use escaping, as Fred suggested, using mysqli_real_escape_string:
$userid = mysqli_real_escape_string($conn, $_POST['userid']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
I'd suggest also looking at using bound parameters and a prepared statement instead, for added extra security.
Use prepared statements, or PDO with prepared statements, they're much safer.

#andrewsi answered correct: "You're running your query twice. The first time, you're assigning the result to $sql; the second time, you're trying to run that result as a query."

#andrewsi, you r running your query twice and your your query contains variables which you have make them as literals. so code would be like this:
$sql ="INSERT INTO forgot(userid,email,mobile)VALUES ($userid,$email,$mobile)";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
I hope this will help you.

Here is a basic example. Check where you have a turn. Always keep follow the standard way of coding.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>

Ankit, their are few things to take care of while coding the queries, instead of explaining them, I will try to rewrite the query:
$query = sprintf("INSERT INTO forgot('userid','email','mobile')
VALUES ('%s', '%s', '%s')"
, mysqli_real_escape_string( $con, $_POST['userid'] )
, mysqli_real_escape_string( $con, $_POST['email'] )
, mysqli_real_escape_string( $con, $_POST['mobile'] ));
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted" . mysqli_affected_rows($conn) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
if in case, userid is the integer, convert the userid to int as follows before creating the $query:
$userid = (int)$_POST['userid'];

$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
It will work.

Related

duplicate row formed in table when using PHP to store a form

I am making a site to display the family relations of an individual...I made use of PHP to store data from a form. I use access code to categorize different relations if an individual. i.e..101-the relations of person X.
I need a bit of help as to why to an entry is being entered twice into the database.(new to PHP and first time asking for help here)
Thank you in Advance!
forms code(IN ct.php):
<form id="frm1" action="ap.php" method="POST">
access code: <input type="text" name="code_entered" value=""><br><br>
position in family: <select name="fpos_entered">
<option>Grandfather</option>
<option>Grandmother</option>
<option>Father</option>
<option>Mother</option>
<option>Brother</option>
<option>Sister</option>
<option>Uncle</option>
<option>Aunt</option>
<option>Nephew</option>
<option>Niece</option>
<option selected>Yourself</option>
</select><br><br>
name: <input type="text" name="name_entered" value=""><br><br>
DOB:<input type="date" name="dob_entered" value=""><br><br>
<input type="submit" value="Submit">
</form>
i use the following PHP code to store the data from the form:
<?php
include 'ct.php';
$temp="temp";
$conn= mysqli_connect ('localhost','root','','familytree');
if (!$conn)
{
die ('Could not connect:' . mysql_error());
}
if (isset($_POST['code_entered']))
{
$acc= $_POST['code_entered'];
}if (isset($_POST['fpos_entered']))
{
$fpos= $_POST['fpos_entered'];
}if (isset($_POST['name_entered']))
{
$n= $_POST['name_entered'];
}if (isset($_POST['dob_entered']))
{
$db= $_POST['dob_entered'];
}
$sql ="insert into temp values ('$acc', '$n','$fpos','$db')";
$result = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
which results in me having :
pic of the database after 2 enteries
<?php
declare(strict_types=1);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "familytree";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
try {
$stmt = $conn->prepare("
INSERT INTO `temp` (code, fpos, name, dob)
VALUES (:code, :fpos, :name, :dob)");
$stmt->bindParam(':code', $_POST['code_entered'] ?? null);
$stmt->bindParam(':fpos', $_POST['fpos_entered'] ?? null);
$stmt->bindParam(':name', $_POST['name_entered'] ?? null);
$stmt->bindParam(':dob', $_POST['dob_entered'] ?? null);
$stmt->execute();
echo "<p>New record created successfully</p>.";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
I recommend you to use PDO instead of mysqli. Also, bind the attributes coming from outside :)
Official docu: https://www.w3schools.com/php/php_mysql_prepared_statements.asp
you can change the code of this
$result = mysqli_query($conn,$sql);
if ($conn->query($sql) === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
into this
$result = mysqli_query($conn,$sql);
if ($result === TRUE) {
echo "<p>New record created successfully</p>.";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
and also you must to be careful about sql injection so i think you must use this

Trying to get username from one database and paste it with a message to another database

I'm currently trying to set up a chat. It works fine on its own, however when I try and get the username from another database for a log in system I have instead of having people choose a username then and there, the system breaks down and doesn't upload the messages to the database. I get no errors.
Here's the code:
<?php
$mysqli = new mysqli("localhost", "root", "", "forum");
$mysqli2 = new mysqli("localhost", "root", "", "login");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (isset($_GET['message']) && isset($_GET['username'])) {
$user=$mysqli2->real_escape_string($_GET['username']);
$message=$mysqli->real_escape_string($_GET['message']);
$date=date('Y-m-d H:i:s');
$sql="INSERT INTO forum(id, user, message, date) VALUES(0,'$user','$message','$date')";
$mysqli->query($sql);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Forum</title>
</head>
<body>
<h2>Forum Messages:</h2>
<?php
$sql = "SELECT * FROM forum";
$result = $mysqli->query($sql);
$sql2 = "SELECT * FROM users";
$result2 = $mysqli2->query($sql2);
while($row = $result->fetch_assoc() && $row2 = $result2->fetch_assoc()) {
echo $row2['username'].', '.$row['date'].' <br>';
echo $row['message'].'<br>';
echo '------------------------ <br>';
}
?>
<form method="get" action="forum.php">
<p>Message:<br>
<label for="message"></label>
<textarea name="message" id="message" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="submit" id="submit" value="Post message">
</p>
</form>
</body>
</html>
Anyone got an idea of why its not working?
You get no errors because you're not checking for any. It's probable that the insert is failing. Your call to query() will return FALSE in this case, so you'll need to check for that.
$sql = "INSERT INTO forum(user, message, date) VALUES('$user','$message','$date')";
if ($mysqli->query($sql) === false) {
throw new Exception('Error performing insert: ' . $mysqli->error);
}
Also note, in this following code, you're not aborting, you just print the error message and then continue on with the script anyway:
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Change the echo to a throw so the script stops.
And ideally, you want to use prepared statements instead of real_escape_string(). Something like this:
$stmt = $mysqli->prepare('INSERT INTO forum(user, message, date) VALUES(?, ?, ?)');
if ($stmt === false) {
// prepare failed
}
$stmt->bind_param('sss', $_GET['username'], $_GET['message'], date('Y-m-d H:i:s'));
if ($stmt->execute() === false) {
// exec failed
}

text versioning system using PHP MySQL

I am trying to create a system where a user can enter some text and another user can edit that input and another can edit the input that the second user has entered. This is the code that I have so far; it only works as a reply system to a post at the moment:
<?php
include 'includes/connection.php';
$query = "SELECT * FROM branches";
$result1 = mysql_query($query) or die(mysql_error());
while($person = mysql_fetch_array($result1)) { //As long as there is data, output the data
$id = $person['ID'];
$query2 = "SELECT * FROM branchesedit WHERE (parent_id = '$id' )";
$result2 = mysql_query($query2) or die(mysql_error());
echo "<h3>" . $person['Names'] . "</h3>";
echo "<p>" . $person['Lyrics'] . "</p>";
echo "Modify Song";
echo "<span> </span>";
echo "Delete Song";
while($row2 = mysql_fetch_array($result2)){
echo "<h3>" . $row2['Name'] . "</h3>";
echo "<p>" . $row2['LyricUpdate'] . "</p>";
}
}
?>
modify.php
<?php
if(isset($_POST['submit'])) {
$query = "SELECT ID FROM branches WHERE ID = $_GET[id]";
mysql_query("INSERT into branchesedit(`IDs`, `Name`, `LyricUpdate`, `parent_id`)
VALUES ('','$_POST[inputName]', '$_POST[ta]', '$_POST[id]')") or die(mysql_error());
echo "Song has been modified";
header("Location: index.php");
}
?>
Note:
You are using an isset() function on your modify.php where in your first given code (guessing your index.php) does not have a submit button. Only has a link that will redirect users to modify.php.
Better include a connection in your modify.php to establish connection so you can run your query.
You should consider using mysqli_* prepared statement rather than the deprecated mysql_* functions to prevent SQL injections.
Your modify.php in prepared statement:
<?php
/* INCLUDE HERE YOUR CONNECTION */
if(!empty($_GET['id'])) {
if($stmt = $con->prepare("SELECT IDs, Name, LyricUpdate FROM branchesedit WHERE parent_id = ? ORDER BY IDs DESC")){
$stmt->bind_param("i",$_GET["id"]);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id,$name,$lyricupdate);
$stmt->fetch();
?>
<h1>Modified by: <?php echo $name; ?></h1>
<form action="modify.php" method="POST">
<input type="hidden" name="id" value="<?php echo $_GET["id"]; ?>">
<input type="text" name="inputName" value="<?php echo $name; ?>"><br>
<textarea name="ta"><?php echo $lyricupdate; ?>"></textarea><br>
<input type="submit" name="submit">
</form>
<?php
$stmt->close();
} /* END OF PREPARED STATEMENT */
} /* END OF NOT EMPTY ID */
if(isset($_POST["submit"])){
if($stmt = $con->prepare("INSERT into branchesedit (`Name`, `LyricUpdate`, `parent_id`)
VALUES (?,?,?)")){
$stmt->bind_param("ssi",$_POST["inputName"],$_POST["ta"],$_POST["id"]);
$stmt->execute();
$stmt->close();
} /* END OF INSERT PREPARED STATEMENT */
echo "Song has been modified";
header("LOCATION: index.php");
} /* END OF ISSET SUBMIT */
?>
Summary:
When a user clicks on Modify Song link, user will be redirected to modify.php and then runs a query that will select the latest edit from your table branchesedit based from the ID being passed from the link.
User will see a form that is already filled up based from the last edit.
When submitted, it will still be in the modify.php and then runs an insert query.
After the insert query, it will redirect back to index.php
Replace the necessary connection variable I used in the prepared statement:
Example of your connection to be included in your queries (connection.php):
$con = new mysqli("Yourhost", "Yourusername", "Yourpassword", "Yourdatabase");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

Query was empty while submitting the form

/Form design/
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form name="form1" method="post" action=""><label><center>Register Form</center></label>
<p><center></center><label>Name:</label>
<input type="text" name="name"></center>
</p>
<p><label>Rollno:</label>
<input type="text" name="rno">
</p>
<p><label>Address:</label>
<input type="text" name="add">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>
</form>
/***********PHP******************/
/Form submission/
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("alpha") or die( "Unable select database");
// Check connection
// escape variables for security
$name = mysql_real_escape_string($_POST['name'],$con);
$rno = mysql_real_escape_string( $_POST['rno'],$con);
$add = mysql_real_escape_string($_POST['add'],$con);
$sql=mysql_query("INSERT INTO test (name, rno, add)
VALUES ('$name','$rno','$add')",$con);
$result=mysql_query($sql) or die(mysql_error());
if (!mysql_query($result,$con)) {
die(mysql_error($con));
}
echo "1 record added";
mysql_close($con);
?>
</body>
</html>
some one please help me with this error.
i am getting the message query was empty.
how can i fix this.
i am new to php and my sql.
i dont know how to solve this issue.
mysql_query should execute a query :
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("alpha") or die( "Unable select database");
// Check connection
// escape variables for security
$name = mysql_real_escape_string($_POST['name'],$con);
$rno = mysql_real_escape_string( $_POST['rno'],$con);
$add = mysql_real_escape_string($_POST['add'],$con);
$query = sprintf("INSERT INTO test (name, rno, add)
VALUES ('%s','%s','%s')", $name, $rno, $add);
$result = mysql_query($query, $con);
if (!$result) {
$message = 'Invalid request : ' . mysql_error() . "\n";
$message .= 'Your query : ' . $query;
die($message);
}
// #see http://php.net/manual/en/function.mysql-affected-rows.php
echo mysql_affected_rows() + " record added";
mysql_close($con);
?>
Try this
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("alpha") or die( "Unable select database");
// Check connection
// escape variables for security
$name = mysql_real_escape_string($_POST['name']);
$rno = mysql_real_escape_string( $_POST['rno']);
$add = mysql_real_escape_string($_POST['add']);
$sql=mysql_query("INSERT INTO test (name, rno, add) VALUES ('$name','$rno','$add')",$con);
if ($sql) {
echo "1 record added";
}
else {
die(mysql_error($con));
}
mysql_close($con);
First of all, if you have kept your html form code and php code in the same page, you will need a conditional operator to check whether the form has been submitted or not. In your code above, the php code are executed even when the form is not submitted.
Make sure your form data are fetched by using any of the following:
var_dump($_POST);
print_r($_POST);
If it displays the data you have entered then so far you are good.
In your code above you have:
$result=mysql_query($sql) or die(mysql_error());
When you have done the above, you will not need the following code as the die() function will do the same. And the following code will also make your query run twice.
if (!mysql_query($result,$con)) {
die(mysql_error($con));
}

php form not writing form data into mysql database

I have to code below - updated
php code
if(empty($_POST['formEmail']))
{
$errorMessage .= "<li>You forgot to enter your email</li>";
}
$varEmail = $_POST['formEmail'];
if(empty($errorMessage))
{
$db = mysql_connect("servername","username","password");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("tableName" ,$db);
$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";
mysql_query($sql);
echo "Details added";
$_SESSION['status'] = 'success';
}
exit();
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
form code
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
<label for='formEmail'>Sign up to be notified when we go live!</label><br/>
<input type="text" name="formEmail" maxlength="50" value="<?=$varEmail;?>" />
</p>
<input type="submit" name="formSubmit" value="Submit" />
</form>
I'm not getting any errors and as far as I can tell the syntax looks fine but its not putting the email information into the database. Anyone have an idea of whats going on? As a side note I am a newb to all php.
You've forgotten to run the query! Put
mysql_query($sql);
straight after
$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";
Make sure you run the $_POST variable through mysql_real_escape_string as well:
$varEmail = mysql_real_escape_string($_POST['formEmail']);
This will help protect you from SQL Injection attacks.
EDIT
One more tiny thing, I guess you want to set the session variable success when the form has submitted successfully. to do that you'll need to move
echo "Details added";
$_SESSION['status'] = 'success';
within the same if structure as the SQL query is run, otherwise it will never be set
Try:
$db = mysql_connect("servername","username","password");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("tableName" ,$db);
$sql = sprintf("INSERT INTO emails(email) VALUES ('%s')",mysql_real_escape_string($varEmail));
$results = mysql_query($sql);

Categories