Query was empty while submitting the form - php

/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));
}

Related

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
}

Getting an error of SQl Syntax

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.

Transferring MySQL server to php page = query not working?

I was trying to make a php page that would display a MySQL search engine, and itworked on one server: however, on that server crashed and I was forced to reboot it. Even when I'm using the same code, the search engine no longer works - my code is as follows:
<html>
<head>
<meta charset="UTF-8">
<title>Search Engine Test</title>
<h1>Gromax</h1>
</head>
<body>
<form action="search1.php" method="post">
<input type="text" name="keyword">
<input type="submit" name="search" value="Search">
<br>
<br>
</form>
<script language="php">
// Create a database connection
error_reporting(0);
$connection = mysql_connect("localhost", "$ mysql -u anonymous", "");
if (!$connection) {
die("Please reload page. Database connection failed: " . mysql_error());
}
// Select a databse to use
$db_select = mysql_select_db("test", $connection);
if (!$db_select) {
die("Please reload page. Database selection failed: " . mysql_error());
}
// Search Engine
// Only execute when button is pressed
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim($_POST['keyword']);
// Select statement
$search = "SELECT Price FROM table_1 WHERE Model = '$keyword'";
// Display
$result = mysql_query($search) or die('query did not work');
while ($result_array = mysql_fetch_array($result)) {
$arrlength=count($result_array);
for($x=0;$x+1<$arrlength;$x++){
echo "Price: " . $result_array[$x];
echo "<br>";
}
}
}
?>
</script>
</body>
</html>
Any help would be appreciated.
I'm pretty sure you have an error in your query or your Database connection. Try commenting the line:
// error_reporting(0);
and see what error you get...
Try to use a format like this to determine what is going wrong in your select query:
<?php
$sql = "
SELECT
Price
FROM
table_1
WHERE
Model = '".$keyword."'
";
if(!$res = mysql_query($sql))
{
trigger_error(mysql_error().'<br />In query: '.$sql);
}
elseif(mysql_num_rows($res) == 0)
{
echo 'Geen resultaten gevonden';
}
else
{
while($row = mysql_fetch_assoc($res))
{
echo $row['voornaam'].'<br />';
}
}
?>

Php sql, form resubmits on page load

Neglecting the obvious security flaws of mysql and nor sql escape strings, does anybody know why my sql tables are getting filled up with empty msgs on page reload.
Every sinngle time the page reloads a form submits. I'm confused as to why this is happening, and how do i stop it?
<?php
ob_start();
session_start();
$con = mysql_connect("localhost","username","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$dates = date('Y-m-d H:i:s');
$uid = $_SESSION['user_id'];
$msg_id = (int) $_GET['msg_id'];
mysql_select_db("db_table", $con);
$result = mysql_query("SELECT users.first_name, users.last_name , intro.intro, intro.outro FROM intro INNER JOIN users ON intro.user_id = users.user_id WHERE intro.message_id = {$msg_id}");
while($row = mysql_fetch_array($result))
{
echo "<div id=\"start\"><div class=\"namedate\"><h1>". $row['first_name'] ." ". $row['last_name'] . "</h1><h2>test</h2></div><div id=\"holdmsg\"><div class=\"cent\"><strong>" . $row['intro'] . "</strong><br><i>" . $row['outro'] ."</i></div></div></div> " ;
}
PART RELEVANT TO THE FORM is this part and also the $_GET, at the top of the page.
<form action="" method="post">
<?php
$sql="INSERT INTO messages (user_id, intro_id , msg, date ) VALUES (('$uid'), {$msg_id} ,'$_POST[msg]', ('$dates'))";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
<textarea rows="2"style="float:left" name="msg" type="text"placeholder="Elaborate on your idea..."></textarea>
<input id="togz2" style="float:right; "type="submit" value="SUBMIT" name="submit" class="butts">
</div></div>
</form>
Why not do it like this?
if (mysql_query($sql,$con))
{
header('location:yourpage.php');
}else{
die('Error: ' . mysql_error());
}
Also I dont see any such statement above your insert query
Like
if(isset($_REQUEST['submit'])){ //to check if posted
$sql="INSERT ......
}
Beside that you should also validate your data before inserting into a database.
Here is good example how to prevent duplicate entry on page load
Please refer link http://www.webhostingtalk.com/showthread.php?t=700175.
<?php
session_start();
$faction = $_REQUEST['faction'] ;
if (!is_array($_SESSION['serials'])) $_SESSION['serials'] = array ();
if ($_REQUEST['serial']){
if ( in_array ($_REQUEST['serial'] , $_SESSION['serials'] ) ){
// duplicate submition, nullify it
$faction = '';
}else{
$_SESSION['serials'][] = $_REQUEST['serial'] ;
}
}
if ($faction) { // form submited
// if faction is not set completely ignore submition
}
?>
<form>
<input type="hidden" name="faction" value="42">
<input type="hidden" name="serial" value="<?=rand(1000000 , 9999999)?;>">
....
the rest of the form is here
....
</form>
Another Solution:-
You should re-direct to a new page after successful insertion.

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