Can't find source of PHP SQL loop - php

Simple question for you guys - I'm trying to submit data to a table in a database and it does so successfully, before continuing to add an infinite number of blank rows to the table.
Here's the code:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$about = $_POST['about'];
$msg = $_POST['message'];
$con = mysql_connect("DATABASE","USERNAME","PASSWORD");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$database = mysql_select_db("benpearl_co_uk_db", $con);
if(!$database) {
die('Houston, we have a problem: ' . mysql_error());
}
$sql="INSERT INTO contact (name, email, about, message) VALUES ('$name', '$email', '$about', '$msg')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
?>
<script language="JavaScript">
self.location="?email=1";
</script>
Just to reiterate, I have no problem in connecting to the database or successfully putting the values from the form into the table. However once the values are inputted the page continually refreshes, adding blank lines to the table.
What's going wrong with my code here?

You always redirect to the the same page with:
self.location="?email=1";
Try something like:
$sql = "INSERT INTO contact (name, email, about, message) VALUES ('$name', '$email', '$about', '$msg')";
if (mysql_query($sql, $con))
{
header('Location: $other_page');
}
die('Error: ' . mysql_error());

The problem is here:
<script language="JavaScript">
self.location="?email=1";
</script>
Self.location redirects the browser, you are redirecting to the same page with the addition of the url parameter email = 1 which of course runs the script again causing an infinite loop. You should check whether $_POST contains valid values and only then insert into the database.

Well, that's exactly what your code does:
on the server side write a DB row
return page to client, that contains <script language="JavaScript">self.location="?email=1";</script>
which in turn makes the page refresh.
You would need to make the JS part conditional.

you should run the insert only when the button submit is clicked if you have , so even when you load the page again it will not insert again the data
try doing this
if (isset($_POST['submit'])) //then run your insert sql
{
$sql="INSERT INTO contact (name, email, about, message) VALUES ('$name', '$email', '$about', '$msg')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
}

Related

Inserting data into multiple different data tables

I was trying to insert data into multiple data tables. It's only working for single data tables, I'm just wondering how I would be able to insert data into two data tables. I've been struggling with this issue for the past few hours and can't seem to get to the bottom of it. If anyone has any advice please let me know. :)
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost","ivodatat","","");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Inputs for security
$fname = mysqli_real_escape_string($link, $_REQUEST['fname']);
$sname = mysqli_real_escape_string($link, $_REQUEST['sname']);
$address = mysqli_real_escape_string($link, $_REQUEST['address']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
$phone = mysqli_real_escape_string($link, $_REQUEST['phone']);
$mac = mysqli_real_escape_string($link, $_REQUEST['mac']);
$installer = mysqli_real_escape_string($link, $_REQUEST['installer']);
$status = mysqli_real_escape_string($link, $_REQUEST['status']);
// Insert Query
$sql1 = "INSERT INTO leadlist (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
$sql2 = "INSERT INTO $installer (fname, sname, address, email, phone, mac, installer, status) VALUES ('$fname', '$sname', '$address', '$email', '$phone', '$mac', '$installer', '$status')";
if (mysqli_multi_query($link, $sql1, $sql2)){
mysqli_close($conn);
header("Location: installercontrol.php");
exit;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close The Connection
mysqli_close($link);
?>
To use mysqli_multi_query you need to append the queries to each other as it only takes one query argument. From the manual:
Executes one or multiple queries which are concatenated by a semicolon.
Try this instead:
mysqli_multi_query($link, $sql1 . ';' . $sql2)
You should probably also update your error message:
echo "ERROR: Could not able to execute $sql1;$sql2. " . mysqli_error($link);

Unable to insert data into MySQL database using PHP

I am unable to insert data into MySQL database. I do not know the reason since no error is triggered. I am using XAMPP on windows to run local server. Here is the code. It would be great if someone could help.
I am always getting "Values not inserted" output. I also tried printing the $query when I got exact values I entered through a form in the VALUES ('$email', ...) part of the SQL query.
<?php
$dbconnect = mysqli_connect("localhost","root","","id3626001_login_details");
if (!$dbconnect)
{
die("Connection Failed" .mysqli_connect_error());
}
if (!mysqli_select_db($dbconnect, "id3626001_login_details"))
{
echo "Could not connect to Database";
}
if (isset($_REQUEST['username']) && ($_SERVER["REQUEST_METHOD"] == "POST")){
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
// Inserting values into the database through a query
$query = "INSERT INTO user_registration (ID, email, username, password) VALUES ('$email', $username', '".md5($password)."')";
if (!mysqli_query($dbconnect, $query))
{
echo "Values not inserted";
}
$result = mysqli_query($dbconnect, $query);
if($result){
echo "Registration Successful";
}
}
?>
there is a problem in your query,
1) your column counts and count of values you are passing are not the same (must be same
2) you forgot to put ' (quote befor $username')
change your query to
// Inserting values into the database through a query
$query = "INSERT INTO user_registration ( email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
When you are testing you should not only print only query, you should also copy that query and run it directly into database through [(localhost/phpmyadmin)> select your databse > SQL ] and see what error are displaying there when firing a query.
UPDATE
for #Akintunde 's suggestion
for security concerns you should not be using these kind of insertion methods which is fully open to SQL injections you must follow some rule to avoid to get your script being target of sql injection
use Prepared Statements instead for database operations
Here in your query you forgot to put upper quote '-> $username',
$query = "INSERT INTO user_registration (email, username, password) VALUES ('$email', '$username', '".md5($password)."')";
Here we are not passing Id as a param so you need to make id auto increment in database for that table.
and why are to passing your query twice into mysqli_query() you can check for once like,
$result = mysqli_query($dbconnect, $query);
if ($result)
{
echo "Registration Successful";
}
else{
echo "Values not inserted";
}

PHP Code inserts Blank Records in MySql database with _POST method

PHP code is inserting blank records when inserting data in the database with the _POST Method, However when I use _GET everything works fine.
Thanks in Advace.
<?php
$con=mysqli_connect("localhost","root","*******","student");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Student (textnames, fathername, mom, occu, homenum, paddress, offcontact, Course, District, State, pincode, emailid, dob, mobileno)
VALUES
('$_POST[textnames]','$_POST[fathername]','$_POST[mom]','$_POST[occu]','$_POST[homenum]','$_POST[paddress]','$_POST[offcontact]','$_POST[Course]','$_POST[District]','$_POST[State]','$_POST[pincode]','$_POST[emailid]','$_POST[dob]','$_POST[mobileno]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Successfully Added Record";
mysqli_close($con);
?>
Any suggestions how to avoid this.....
a good rule of thumb is checking PHP Variables availability with phpinfo (this is related to your web server configuration).
Try and add:
echo phpinfo();
exit;
just before your
if (!mysqli_query($con,$sql))
The reason is that you are most probably doing the post not same as get
'$_POST[textnames]'// is wrong
'$_POST["textnames"]'// is correct
and same with all others. You must have used quotes to get these values without quotes your index like textnames would be incorrect both for GET and POST
try to initialise the $_POST to a local variable and use the query as follows
<?php
$a=$_POST['textname'];
$b=$_POST['fathername'];
$c=$_POST['mom'];'
$d=$_POST['occu'];
$e=$_POST['homenum'];
$f=$_POST['paddress'];
$g=$_POST['offcontact'];
$i=$_POST['Course'];
$j=$_POST['District'];
$k=$_POST['State'];
$l=$_POST['pincode'];
$m=$_POST['emailid'];
$o=$_POST['dob'];
$p=$_POST['mobileno']
$con=mysqli_connect("localhost","root","*******","student");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Student (textnames, fathername, mom, occu, homenum, paddress, offcontact, Course, District, State, pincode, emailid, dob, mobileno) VALUES('$a','$b','$c','$d','$e','$f','$g','$i','$j','$k','$l','$m','$o','$p')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Successfully Added Record";
mysqli_close($con);
?>
First check whether your form is sending value by
if(isset($_POST["submit"]))
{
Your insert query here
}
also in form try using following code
<form methode = "POST" action = "">
</form>
It works with the _REQUEST i think it'll do
<?php
$con=mysqli_connect("localhost","root","********","student");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Student (textnames, fathername, mom, occu, homenum, paddress, offcontact, Course, District, State, pincode, emailid, dob, mobileno)
VALUES
('$_REQUEST[textnames]','$_REQUEST[fathername]','$_REQUEST[mom]','$_REQUEST[occu]','$_REQUEST[homenum]','$_REQUEST[paddress]','$_REQUEST[offcontact]','$_REQUEST[Course]','$_REQUEST[District]','$_REQUEST[State]','$_REQUEST[pincode]','$_REQUEST[emailid]','$_REQUEST[dob]','$_REQUEST[mobileno]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Successfully Added Record";
mysqli_close($con);
?>
You can change your code like this. The point is you missed the single quotes when accessed the post variables.
<?php
$con=mysqli_connect("localhost","root","*******","student");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Student (textnames, fathername, mom, occu, homenum, paddress, offcontact, Course, District, State, pincode, emailid, dob, mobileno)
VALUES
('".$_POST['textnames']."','".$_POST['fathername']."','".$_POST['mom']."','".$_POST['occu']."','".$_POST['homenum']."','".$_POST['paddress']."','".$_POST['offcontact']."','".$_POST['Course']."','".$_POST['District']."','".$_POST['State']."','".$_POST['pincode']."','".$_POST['emailid']."','".$_POST['dob']."','".$_POST['mobileno']."')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Successfully Added Record";
mysqli_close($con);
}
}
?>

Where to put "mysql_real_escape_string" in this code?

I've looked at other examples on here, but everyone else's syntax is different from what I have, so I have no clue where to put "mysql_real_escape_string".
Here is my current code:
include("dbconnect.php");
mysql_select_db("scratch", $con);
$sql= "INSERT INTO stories (author, story_name, story)
VALUES
('$_POST[author]','$_POST[story_name]', '$_POST[story]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Story Submitted!";
mysql_close($con)
Where would I add that string in this?
You need to escape any variable values you're including in your query. So in your code these would be:
$_POST['author']
$_POST['story_name']
$_POST['story']
So change your $sql variable to look like:
$author = mysql_real_escape_string($_POST['author']);
$story_name = mysql_real_escape_string($_POST['story_name']);
$story = mysql_real_escape_string($_POST['story']);
$sql= "
INSERT INTO stories (author, story_name, story)
VALUES ('$author','$story_name', '$story')
";
You should probably also add isset or empty checks when using the $_POST variables to avoid notices if they don't exist. Finally, you'd be better served to use PDO with prepared statements than the less robust mysql extension.
//USE IN THIS WAY THE QUERY WILL RUN PROPERLY WITH mysql_real_escape_string
$sql= 'INSERT INTO stories (author, story_name, story)
VALUES
('.mysql_real_escape_string($_POST[author]).',
'.mysql_real_escape_string($_POST[story_name]).',
'.mysql_real_escape_string($_POST[story]).')';
put POST variables into new variables and then apply mysql_real_escape_string, and finally put new variables into the SQL statement
Here's the code:
include("dbconnect.php");
mysql_select_db("scratch", $con);
$author = mysql_real_escape_string($_POST[author]);
$story_name = mysql_real_escape_string($_POST[story_name]);
$story=mysql_real_escape_string($_POST[story]);
$sql= "INSERT INTO stories (author, story_name, story)
VALUES
('$author','$story_name', '$story')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Story Submitted!";
mysql_close($con);

Unable to update database using php

I have a the following code for inputing data in a database..i specifically echoed the values to see whether they have correct values or not...they have correct values but the values i get in the database are totally different.
Here is my code
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sm_sample");
$source=$_POST['source'];
$username=$_POST['username'];
$location=$_POST['location'];
$category=$_POST['category'];
$complaint=$_POST['complaint'];
$status=$_POST['status'];
$date=$_POST['date'];
echo $source.$username.$location.$category.$complaint.$status.$date;
$sql="INSERT INTO sample VALUES(ID=NULL,source='$source',username=
'$username', location='$location', category='$category',complaint=
'$complaint',date='$date',status='$status')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
echo "<BR>";
echo "<a href='usercom1.php'>View result</a>";
mysql_close($con)
?>
the values i get in the database r like this:
List data from mysql
Source Username Location Category Complaint Date Status Update
0 Singapore 0 0000-00-00 Pending Edit
The correct syntax:
$sql="INSERT INTO `sample`(`ID`,`source`,`username`, `location`,`category`,`complaint`,`date`,`status`)
VALUES (0, '$source','$username','$location','$category','$complaint','$date','$status')";
later edit ... you are using wrong mysql_query and connection syntax
$con = mysql_connect("localhost","root","") or die('database connection?');
mysql_select_db("sm_sample", $con) or die('wrong database?');
// and for $_POST you sould use mysql_real_escape_string
$source = mysql_real_escape_string($_POST['source']);
// ........................................
$sql="INSERT INTO `sample`(`ID`,`source`,`username`, `location`,`category`,`complaint`,`date`,`status`)
VALUES (0, '$source','$username','$location','$category','$complaint','$date','$status')";
mysql_query($sql) or die('Error: '.mysql_error().': '.mysql_errno());
// ........................................
mysql_close($con);
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
echo ('Could not connect: ' . mysql_error());
}
mysql_select_db("sm_sample",$con);
$source=$_POST['source'];
$username=$_POST['username'];
$location=$_POST['location'];
$category=$_POST['category'];
$complaint=$_POST['complaint'];
$status=$_POST['status'];
$date=$_POST['date'];
echo $source.$username.$location.$category.$complaint.$status.$date;
$sql="INSERT INTO sample ('source','username','location','category','complaint','status') VALUES('$source','$username','location','category','complaint','status' )";
if (!mysql_query($sql))
{
echo ('Error: ' . mysql_error());
}
echo "1 record added";
echo "<BR>";
echo "<a href='usercom1.php'>View result</a>";
mysql_close($con);
?>
First thing you do not have to add id if it is auto increment and date if it uses current timestamp and one more thing that never use die(); , use echo instead.
You should provide only VALUES of data with no column names:
$sql="INSERT INTO sample VALUES(ID, '$source', '$username', '$location', '$category', '$complaint', '$date', '$status')";
Also if you have only one DB connection you can not to define $con variable in mysql_query(). Like this: mysql_query($sql).
The problem is with the following line:
<?php
$sql="INSERT INTO sample VALUES(ID=NULL,source='$source',username='$username', location='$location', category='$category',complaint=
'$complaint',date='$date',status='$status')";
?>
If you check the result in the database, you'll see that the values are getting in the wrong order, use this instead:
<?php
$sql="INSERT INTO sample(ID, source, username, location, category, complaint, date, status) VALUES(NULL, '$source', '$username', '$location', '$category', '$complaint','$date','$status')";
?>
PLEASE read what Albireo posted in his comment. Your code is extremely vulnerable.

Categories