Error with simple PHP form with MySQL - php

Sirs,
I'm getting an error from my PHP script, probably the query, but I can't figure out what's going on. I can connect the database, but I still get the error from de "echo ERROR" line.
Does anyone know what's wrong with my code? I appreciate any help! I spent a few hours to solve this issue, but couldn't get nothing.
HTML form
<form action="insert-info.php" method="post">
<input class="form1" type="text" value="TEXT ONE" name="textone" onfocus="if (this.value=='NTEXT ONE') this.value='';"/>
<input class="form1" type="text" value="TEXT TWO" name="texttwo" onfocus="if (this.value=='TEXT TWO') this.value='';"/>
<input class="form2" type="text" value="TEXT THREE" name="textthree" onfocus="if (this.value=='TEXT THREE') this.value='';"/>
</form>
Database connect and insert
<?php
$host="localhost"; // Host name
$username="***"; // Mysql username
$password="***"; // Mysql password
$db_name="***"; // Database name
$tbl_name="insertinfo"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$textone=$_POST['textone'];
$texttwo=$_POST['texttwo'];
$textthree=$_POST['textthree'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name('textone', 'texttwo', 'textthree') VALUES ('$textone', '$texttwo', '$textthree')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<br />";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
Database structure
# Type Collation Null Pattern Extra
1 id int(4) None (none) AUTO_INCREMENT
2 textone varchar(50) utf8_bin None (none)
3 texttwo varchar(50) utf8_bin None (none)
4 textthree varchar(50) utf8_bin None (none)

Looks like the issue is just the column names of your INSERT query. You don't need single quotes around those.
$sql="INSERT INTO $tbl_name(textone, texttwo, textthree) VALUES ('$textone', '$texttwo', '$textthree')";
That should work.
EDIT: echo_Me and Mayank's warnings and recommendations are necessary to consider for production code!

actually you are not selecting database and the connection variables. because you are using strings. you need to remove the quotes like that
mysql_connect($host, $username, $password)or die("cannot connect");
mysql_select_db($db_name)or die("cannot select DB");
there is some things you need to fix in your code .
escape your POST variables.
change to PDO or MYSQLI.
follow the error by echoing system error.

Use mysql_error() to print the error message. It will tell you more about why the query failed. Note that this function is deprecated. I recommend to use mysqli or PDO database classes.

$sql=sprintf(
"INSERT INTO
$tbl_name(textone, texttwo, textthree)
VALUES ('%s','%s','%s')",
mysql_real_escape_string($textone),
mysql_real_escape_string($texttwo),
mysql_real_escape_string($textthree)
);

Try Like this
There is no need to give column names within ' ' in INSERT query.
$sql="INSERT INTO $tbl_name(textone,texttwo,textthree) VALUES ('$textone', '$texttwo', '$textthree')";
$result=mysql_query($sql);

Related

PHP/SQL script only works sometimes

So I have a PHP form that seems to only want to work sometimes. I really don't understand what is wrong with it or why. I will submit test data successfully, but 5 minutes later I will do another test and I get the error message.
I'm not an PHP or SQL expert so help me out!
<?php
$host="localhost"; // Host name
$username="user"; // Mysql username
$password="pass"; // Mysql password
$db_name="database"; // Database name
$tbl_name="table"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$title=$_POST['title'];
$body=$_POST['body'];
$date=$_POST['date'];
$tags=$_POST['tags'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name(title, body, date, tags)VALUES('$title', '$body', '$date', '$tags')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
Thank you!
Louie
For first enable error reporting:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
And check what's going on in your code.
Maybe problem is not in PHP but in MySQL Server.

Forbidden: You don't have permission to access /bijwerkvlucht_post.php on this server

I know this has been asked hundreds of times, however, I couldn't find how this specific error applied to many of the other examples.
I have many form fields on a PHP page and they update into my database just fine when I hit submit, until I use http://somewebsite.net in one of the fields.
The field I post my form, field flightaware is posted to bijwerkvlucht_post.php as flightaware='$flightaware'.
I do not get the above error message when I test with plain text or remove the http:// . Thus deducing that it is an issue related to http:// in the wording.
How would I fix the code to resolve this particular issue?
The code on the post page:
<?php
$host="localhost"; // Host name
$username="xxxxx"; // Mysql username
$password="xxxxx"; // Mysql password
$db_name="xxxxx"; // Database name
$tbl_name="tbl_vluchtgegevens"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE $tbl_name SET reisID='$reisID', vertrekdatum2='$vertrekdatum2',
vertrektijd='$vertrektijd', vertrektijdactueel='$vertrektijdactueel',
vertrekluchthaven='$vertrekluchthaven', aankomstdatum2='$aankomstdatum2',
aankomsttijd='$aankomsttijd', aankomstluchthaven='$aankomstluchthaven',
luchtvaartmaatschappij='$luchtvaartmaatschappij', toestel='$toestel',
inschrijvingnmr='$inschrijvingnmr', vluchttijd='$vluchttijd',
vluchttijddec='$vluchttijddec',reisklasse='$reisklasse', stoel='$stoel', prijs='$prijs',
vluchtnmr='$vluchtnmr', vluchttype='$vluchttype', upgrade='$upgrade',
boekingcode='$boekingcode', eticketnmr='$eticketnmr', farecode='$farecode',
flightaware='$flightaware', route='$route' WHERE gegevenID='$id'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>

Connecting form to database errors

Hello I am trying to connect a page to a MySQL database for newsletter signup. I have the database with 3 fields, id, name, email. The database is named newsletter and the table is named newsletter. Everything seems to be fine but I am getting this error
Notice: Undefined index: Name in C:\wamp\www\insert.php on line 12
Notice: Undefined index: Name in C:\wamp\www\insert.php on line 13
Here is my form code.
<form action="insert.php" method="post">
<input type="text" value="Name" name="Name" id="Name" class="txtfield" onblur="javascript:if(this.value==''){this.value=this.defaultValue;}" onfocus="javascript:if(this.value==this.defaultValue){this.value='';}" />
<input type="text" value="Enter Email Address" name="Email" id="Email" class="txtfield" onblur="javascript:if(this.value==''){this.value=this.defaultValue;}" onfocus="javascript:if(this.value==this.defaultValue){this.value='';}" />
<input type="submit" value="" class="button" />
</form>
Here is my insert.php file.
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="newsletter"; // Database name
$tbl_name="newsletter"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$name=$_POST['Name'];
$email=$_POST['Email'];
// Insert data into mysql
$sql="INSERT INTO $tbl_name(name, email)VALUES('$name', '$email')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='index.html'>Back to main page</a>";
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
The error indicates the index Name is not found in the $_POST[] array. It is a PHP notice, and not a show-stopping error, but rather is intended to communicate that you are referencing a value which does not exist. If it is normal/expected that this value might be empty/null then the notice can be safely ignored.
Beyond this problem, you should be sanitizing public values prior to referencing within the SQL statement, ie:
$name = mysql_real_escape_string($_POST['Name']);
$email = mysql_real_escape_string($_POST['Email']);
A few other notes:
In the call to mysql_connect() it is not necessary to wrap variables $host, $username or $password in quotes. The same is true with $db_name in call to mysql_select_db(). They are already strings as defined in the lines above and so this is excessive.
Perhaps some validation on the values in $_POST[] would be a good idea prior to SQL query? This way you can output an error if, for example, the Name value is empty.

Adding info to a database with php

Hi there doing a small project with databases ( don't have too much experience with them). I'm working with mySQL and php, having a little bit of trouble with the php and posting the info from the HTML form to the database.
Here is the code:
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="tags"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get data that sent from form
$s_name=$_GET['name'];
$s_system=$_GET['system'];
$s_cate=$_GET['cate'];
$sql="INSERT INTO $tbl_name(name,system,cate)VALUES('$s_name', '$s_system', '$s_cate')";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
echo "<a href=mainforum.php>View your topic</a>";
}
else {
echo "ERROR";
}
mysql_close();
?>
If anyone could help explain to me what I am doing wrong, much would very be appreciated.
THANKS
Here is a link to what I am trying to do:
http://socialsoftware.purchase.edu/roger-p.king/database2/enter_gamertag.html
u should use $_POST['variable'], not $_GET
because $_GET is variables array on the link
such as "http://example.com/?var=123", the value of $_GET['var'] is 123
the variable in form can get by $_POST['var'] or $_REQUEST['var']
$query = mysql_query("INSERT INTO '$tbl_name'(name,system,cate)VALUES('$s_name', '$s_system', '$s_cate')";
That should do, or if you do it your way in 2 lines,
$sql="INSERT INTO '$tbl_name'(name,system,cate)VALUES('$s_name', '$s_system', '$s_cate')";
$result=mysql_query($sql);

PHP form not writing to mySQL database

I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database. I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.
Here's the latest version of the code. Could someone please tell me what I am doing wrong?
* Basic HTML Form *
<form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>
<p>Metric1<br />
<input name="metric1" type="text" /></p>
<p>Metric2<br />
<input name="metric2" type="text" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
* Processor File *
<?php
$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
{die('Could not connect to database: ' . mysql_error());}
mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
Print "Your metrics have been successfully added to the database.";
mysql_close($con);
?>
Your mysql-syntax is wrong.
Try
INSERT INTO my_metrics
SET
date = '$date',
metric1 = '$metric1',
metric2 = '$metric2'
Depending on what the table looks like, your code may or may not work,
"INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')"
assumes that the fields are in that order, and that there are no fields before this one.
"INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')"
would be more future proof, and may also solve your problem as they are going to insert into the correct fields.
It is also possible that you are getting some bad data for the field definitions, try doing the insert in phpmyadmin or at the command line instead of in php, then work backwards from there.
As far as the vulnerability to SQL injection, you should feed your input strings to mysql_real_escape_string();. This will escape any unwanted characters.
When connecting to the database, you write
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
You can simplify this, and making this more readable by writing
mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql:<hr>'.mysql_error());
For solving your problem, see if specifieng column names helps. If you don't, mysql will assume you enter values in the order of the columns, you might get some trouble with an ID field, or something like that. Your query could look like this:
"INSERT INTO my metrics (date,metric1,metric2) VALUES ('$data','$metric1','$metric2'))"
And finally, here's a speed concideration.
There are two ways to write strings: using single quotes ('string'), and using double quotes ("string"). in the case of 'string' and "string", they will work exactly the same, but there is a difference. Look at the following code
$age=3
echo 'the cat is $age years old.';
//prints out 'the cat is $age years old.'
echo "the cat is $age years old.";
//prints out 'the cat is 3 years old'
echo 'the cat is '.$age.' years old';
//prints out 'the cat is 3 years old'.
As you can see from this example, when you use single quotes, PHP doesn't check the string for variables and other things to parse inside the string. Doing that takes PHP longer than concatinating the variable to the string. so although
echo "the cat is $age years old"
is shorter to type than
echo 'the cat is '.$age.' years old';
it will boost your page loading when you write larger applications.
Hooray! Hooray! Hooray!
Thank you all for such helpful advice! It finally works! Here's the updated code in case any other newbies have the same issue. (Hope I didn't screw anything else up.)
Form
<form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>
<p>Metric1<br />
<input name="metric1" type="text" /></p>
<p>Metric2<br />
<input name="metric2" type="text" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
Processor
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
// 1. Create connection to database
mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql: <hr>'.mysql_error());
// 2. Select database
mysql_select_db("my_metrics") or die('Could not connect to database:<hr>'.mysql_error());
// 3. Assign variables (after connection as required by escape string)
$date=mysql_real_escape_string($_POST['date']);
$metric1=mysql_real_escape_string($_POST['metric1']);
$metric2=mysql_real_escape_string($_POST['metric2']);
// 4. Insert data into table
mysql_query("INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')");
Echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close()
?>
Here you go love :) try W3c it a good place for new pepps
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO my_metrics (date, metric1, metric2)
VALUES
('$_POST[date]','$_POST[mertric1]','$_POST[metric2]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Your metrics have been successfully added to the database.";
mysql_close($con)
?>

Categories