Php sql, form resubmits on page load - php

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.

Related

How can I stop the page reloading whenever a submit button is pressed?

I'm currently trying to create a system where users of my website can upvote/downvote things. Essentially, the way I'm going about this is by using the following html
<form method='post'>
<input type='submit' name='up' value='up'>
<input type='submit' name='down' value='down'>
</form>
Combined with this php:
<?php
if( isset($_POST['up']) ){
$con = mysqli_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
$postid = "";
$userid = $_SERVER['REMOTE_ADDR'];
$query = "
INSERT INTO database.table (postid, ipaddress, vote) VALUES ('$postid', '$userid', '+1')";
mysqli_query($con, $query);
mysqli_close($con);
}
elseif( isset($_POST['down']) ){
$con = mysqli_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
$postid = "";
$userid = $_SERVER['REMOTE_ADDR'];
$query = "
INSERT INTO database.table (postid, ipaddress, vote) VALUES ('$postid', '$userid', '-1')";
mysqli_query($con, $query);
mysqli_close($con);
}
?>
This works to some extent. As I'd hoped, it keeps track of the current vote count. The problem I wish to tackle here is the fact that every time the up/down button is pressed - the page is reloaded. How can I prevent this from happening, and make this process more fluid?
Thanks in advance for any input.
I realize that you didn't mention jQuery anywhere in your question, but since you can not do what you are trying to do with pure HTML+PHP, I assume you will sooner or later resort to JS to achieve the effect. jQuery is perfect for this case:
HTML part
<a class="voter" data-vote="up">Vote up</a>
<a class="voter" data-vote="down">Vote down</a>
jQuery part (JSFiddle)
$(function(){
$('.voter').click(function(e){
e.preventDefault(); // prevent page reload
var voteType = $(this).data('vote');
$.post('/echo/json/', {
voteType: voteType
}, function(){
alert('You have voted');
});
});
});
PHP part
$voteType = $_POST['voteType'];
switch($voteType){
case 'up':
// Do something
break;
case 'down':
// Do something else
break;
}

POST Data not inserting into sql table

I am using a form. (I wanted the message text as a text area but changed back to normal text to see if this was the problem)
This is the form I am using
<form name="addmessage" method="POST" action="addmessage.php" >
<input type="text" name="message_title" id="message_title">Message Title</input>
<input type="text" name="message_text" id="message_text">Message</input>
<input type="submit" name="submit" value = Add>
</form>
Below is the PHP code. I understand i need to protect against sql injection however, i can do this later.
<?php
include_once("config.php");
if(isset($_POST["message_title"]) && strlen($_POST["message_title"])>0)
{
$message_title=$_POST['message_title'];
$message_text=$_POST['message_text'];
session_start();
$barber_id = $_SESSION['barber_id'];
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
}
else
{
//Output error
header('HTTP/1.1 500 Error You have left it blank');
exit();
}
header("location:messages.php");
?>
If manually enter data using phpMyAdmin, I can get it to display using the code below.
include_once("config.php");
session_start();
$barber_id = $_SESSION['barber_id'];
$results = $mysqli->query("SELECT * FROM messages WHERE barber_id ='$barber_id' ");
//get all records from table
while($row = $results->fetch_assoc())
{
$prices_id = $row['prices_id'];
echo '<div data-role="collapsible">';
echo '<h1>';
echo ' Message Title: ';
echo $row['message_title'];
echo '</a>';
echo '</h1>';
echo '<p>';
echo $row['message_text'];
echo ' Delete</div>';
}
$mysqli->close();
?>
At $insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
you should write
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."','".$message_text."')");
Everytime you pass a String or other non int values you must pass them like that: 'xx', otherwise mysql will see it as query param and it crashes.

I can't get my update query to work (php / mysqli)

I am posting a shortened version of the form and updating lines. I will truly appreciate any help. I have spent the last 48 hours trying all I could think of and it's driving me insane. If I remove the line if($_SERVER["REQUEST_METHOD"]=="POST"), the program runs on loading the page and does update the table at the ID in the url with a blank field. Thanks in advance. Here's the code:
<?php
$id = $_GET['id'];
$user = $_SESSION['user'];
Echo '<form action="editone.php" method="POST">
Enter new name:<input type="text" name="namex" />
<input type="submit" name="Submit" value="Update List" /> </form>';
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $id);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>
I think your form action didn't pass id.
<form action="editone.php" method="POST">
If you're using this single file as form editor and action, your form editor URL should be http://localhost/editone.php?id=1
Try to change your form action to
<form action="editone.php?id='.$_GET['id'].'" method="POST">
or just leave the action blank
<form action="" method="POST">
Ok - maybe I'm way off base here but I see the following problems.
1) Your method is POST however your id is coming from GET.
2) I don't see where the id is coming from. It could be coming from somewhere and not posted but I don't see it.
Have you checked to verify the value is actually being passed through to the php?
try this
echo "GET = " . var_dump($_GET);
echo "<br><br>";
echo "POST = " . var_dump($_POST);
exit();
Post the results and then post where the id is coming from if you can't figure it out still. :)
Use the below code:
$query = "SELECT now_edit, FROM EDITORIES WHERE edit_id='$numb' LIMIT 1";
I assume your page is being called initially from an anchor link on another page which is why you are getting the id from $_GET['id'].
When the user presses the submit button of course the form is being submitted as a POST so all the data will be in $_POST, therefore $_GET['id'] will fail and should be generating an error message.
You need to save the $_GET['id'] from the first instantiation so you can use it when the form is posted to you. So put it in a hidden field that will be posted to you with the post
<?php
session_start();
$user = $_SESSION['user'];
if($_SERVER["REQUEST_METHOD"]=="GET") {
if ( isset($_GET['id']) ) {
$id = $_GET['id']);
} else {
// no param passed, could be a hack
header('Location: some_error_page.php');
exit;
}
echo '<form action="editone.php" method="POST">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo 'Enter new name:<input type="text" name="namex" />';
echo '<input type="submit" name="Submit" value="Update List" /></form>';
}
if($_SERVER["REQUEST_METHOD"]=="POST") {
$dblink = "nn000185_manager";
$cxn = new mysqli("localhost","user","password", $dblink);
$details = mysqli_real_escape_string($cxn, $_POST['namex']);
$numb = mysqli_real_escape_string($cxn, $_POST['id']);
$query = "UPDATE EDITORES SET nom_edit = '$details' WHERE edit_id = $numb";
mysqli_query($cxn, $query);
echo $query;
}
?>

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 not updating correctly on POST

I'm trying to write a function that will allow a user to enter a name into a field, insert the field to a MySQL table and then update a dropdown menu to include those names (while allowing for further additions).
On first load of the page, the dropdown menu shows the correct names that I seeded into the table. When I input a name into the form, it inserts to the table correctly, but then none of the options show in the dropdown list and it removes my entry form. If I refresh the page, everything comes back fine, and the names previously entered show up in the list.
I know I'm missing something obvious in the code to refresh the page, but I'm not even sure what to search for. I thought that by setting my form action to .$_SERVER['PHP_SELF']. it would cause the page to process and reload. I have a hunch this is where my problem is, but I'm not sure what it is.
The dropdown code was something I found off the web, perhaps I have to rewrite it myself, though it's the one part of this mess that's actually working.
Also, the mysql login is hardcoded in db_tools.php b/c I can't get it to work otherwise.
Sorry for the following wall of text, but I'm just trying to provide the most information possible. Thank you for your replies and pointing me in the right direction.
I have 2 files, db_tools.php and dropdown.inc
db_tools.php:
<?php
require_once 'db_login.php';
require_once 'MDB2.php';
require_once("dropdown.inc");
//Define a function to perform the database insert and display the names
function insert_db($name){
//initialize db connection
//$dsn = 'mysql://$db_username:$db_password#$db_hostname/$db_database';
$dsn = "mysql://redacted";
$mdb2 =& MDB2::connect($dsn);
if (PEAR::isError($mdb2)) {
//die($mdb2->getMessage());
die($mdb2->getDebugInfo());
}
//Manipulation query
$sql = " INSERT INTO participants (id, name) VALUES (NULL, \"$name\");";
$affected =& $mdb2->exec($sql);
if (PEAR::isError($affected)){
//die($affected->getMessage());
die($affected->getDebugInfo());
}
//Display query
$query = "SELECT * FROM participants;";
$result =& $mdb2->query($query);
if (PEAR::isError($result)){
die ($result->getMessage());
}
while ($row = $result->fetchRow()){
echo $row[1] . "\n";
}
$mdb2->disconnect();
}
?>
<html>
<head>
<title>Event Bill Splitter</title>
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
else {
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
}
?>
<p>Participants:<br />
<?php dropdown(id, name, participants, name, participant_name1); ?></p>
</body>
</head>
</html>
dropdown.inc
require_once ('db_login.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if (!$connection) {
die ("Could not connect to the database: <br />". mysql_error() );
}
$db_select = mysql_select_db($db_database);
if (!$db_select) {
die ("Could not select the database: <br />". mysql_error() );
}
function dropdown($intNameID, $strNameField, $strTableName, $strOrderField, $strNameOrdinal, $strMethod="asc") {
//
// PHP DYNAMIC DROP-DOWN BOX - HTML SELECT
//
// 2006-05, 2008-09, 2009-04 http://kimbriggs.com/computers/
echo "<select name=\"$strNameOrdinal\">\n";
echo "<option value=\"NULL\">Select Value</option>\n";
$strQuery = "select $intNameID, $strNameField
from $strTableName
order by $strOrderField $strMethod";
$rsrcResult = mysql_query($strQuery);
while($arrayRow = mysql_fetch_assoc($rsrcResult)) {
$strA = $arrayRow["$intNameID"];
$strB = $arrayRow["$strNameField"];
echo "<option value=\"$strA\">$strB</option>\n";
}
echo "</select>";
}
?>
The problem of the form disappearing is simple, just remove the else after the insert section:
<body>
<?php
$name = $_POST['name'];
if ($name != NULL){
insert_db($name);
}
// else { // gone
echo '
<h1>Enter a new participant</h1>
<form name="nameForm" action="'.$_SERVER['PHP_SELF'].'" method="POST">
Name:<input name="name" type="text" />
</form>';
// } // gone
?>
Apart from that I would definitely re-write the dropdown code and add some security, a whitelist for table names, etc.
By the way, you are calling your function in a strange way:
<?php dropdown(id, name, participants, name, participant_name1); ?>
I assume these are variables so it should be $id etc, but where do they come from? If you mean to send values directly, it should be:
<?php dropdown('id', 'name', 'participants', 'name', 'participant_name1'); ?>

Categories