Connecting form to database errors - php

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.

Related

can't insert data in a mysql database using php

first of all i am pretty new with mysql and php and for now i just want to insert some data in a mysql database form two text box using php.
here the database name is "info" and table name is "students" having three columns like id(primary key, auto increment activated), name and dept. There are two text boxes txtName and txtDept. I want that when i press the enter button the data form the text boxes will be inserted into the mysql database. I have tried the following code but data is not being inserted in the table....
<html>
<form mehtod="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info");
if($_POST){
$name = $_POST['txtName'];
$dept = $_POST['txtDept'];
echo $name;
mysqli_query($con,"INSERT INTO students(name,dept) VALUES($name,$dept);");
}
?>
There are a few things wrong with your posted code.
mehtod="post" it should be method="post" - typo.
Plus, quote your VALUES
VALUES('$name','$dept')
DO use prepared statements, or PDO with prepared statements.
because your present code is open to SQL injection
and add error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
You should also check for DB errors.
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
as well as or die(mysqli_error($con)) to mysqli_query()
Sidenote/suggestion:
If your entire code is inside the same file (which appears to be), consider wrapping your PHP/SQL inside a conditional statement using the submit button named attribute, otherwise, you may get an Undefined index... warning.
Naming your submit button <input type="submit" name="submit" value="Enter"/>
and doing
if(isset($_POST['submit'])){ code to execute }
Just doing if($_POST){ may give unexpected results when error reporting is set.
Rewrite: with some added security using mysqli_real_escape_string() and stripslashes()
<html>
<form method="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" name="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = stripslashes($_POST['txtName']);
$name = mysqli_real_escape_string($con,$_POST['txtName']);
$dept = stripslashes($_POST['txtDept']);
$dept = mysqli_real_escape_string($con,$_POST['txtDept']);
echo $name;
mysqli_query($con,"INSERT INTO `students` (`name`, `dept`) VALUES ('$name','$dept')")
or die(mysqli_error($con));
}
?>
As per the manual: http://php.net/manual/en/mysqli.connect-error.php and if you wish to use the following method where a comment has been given to that effect:
<?php
$link = #mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
God save us all...
Use PDO class instead :). By using PDO you can additionally make prepared statement on client side and use named parameters. More over if you ever have to change your database driver PDO support around 12 different drivers (eighteen different databases!) where MySQLi supports only one driver (MySQL). :(
In term of performance MySQLi is around 2,5% faster however this is not a big difference at all. My choice is PDO anyway :).

PHP code not inserting data into MySQL Database

Basically i've been scratching my head at this and I still can't figure out why it's not inserting.
I'm 100% sure the database is connected as it's fetching information just fine, however the following code fails to insert anything into the database. I've checked for spelling mistakes, i've checked from deprecated php code etc, and have used mysqli and mysql.
<?php
include_once "settings.php";
if (isset($_POST['sendMessage']) && isset($_POST['messageTo']) && isset($_POST['messageBody'])){
$messageTo = mysql_real_escape_string($_POST['messageTo']);
$messageBody = mysql_real_escape_string($_POST['messageBody']);
$query= "INSERT INTO inbox (`msgTo`, `msgFrom`, `msgBody`)
VALUES('$messageTo', '$username', '$messageBody')";
if(mysql_query($query))
echo "done.";
else
echo "Problem with Query";
}
?>
<form method="POST">
<div class="searchContain">
<input name="textfield" type="text" name="messageTo" class="input search"><br />
<textarea placeholder="Your message..." name="messageBody" class="input sendmsg" ></textarea><br />
<button class="input" name="sendMessage">Send Message</button>
</div>
</form>
Settings.php:
<?php
session_start();
include_once "../more/config/connect.php";
// Settings //
function logincheck(){
if (!isset($_SESSION['username'])){
header("location: ../index.php");
}
}
logincheck();
$username=$_SESSION['username'];
$gatherInfo=mysql_query("SELECT * FROM users WHERE username='$username' LIMIT 1");
$fetch=mysql_fetch_object($gatherInfo);
?>
connect.php:
<?php
// Connect to the server //
date_default_timezone_set('Europe/London');
mysql_connect("localhost", "root", "connected") or die (mysql_error ());
mysql_select_db("ts") or die(mysql_error());
?>
If anyone could help me fix this rather basic rookie error I'd be very grateful!
UPDATE:
Basically after changing the code. I've gone through the MAMP panel and changed the errors so they display. It's giving me the following error message:
Warning: mysql_connect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2)
in I've never come across this error before, any ideas? It seems to fetch data from the database just fine, so I'm not sure why.
try changing your query to
$query= "INSERT INTO `inbox` (`msgTo`, `msgFrom`, `msgBody`)
VALUES('$messageTo', '$username', '$messageBody')";
you can try the following
if (isset($_POST['sendMessage']) && isset($_POST['messageTo']) && isset$_POST['messageBody'])){
$messageTo = mysql_real_escape_string($_POST['messageTo']);
$messageBody = mysql_real_escape_string($_POST['messageBody']);
$query= "INSERT INTO inbox ('msgTo', 'msgFrom', 'msgBody')
VALUES('$messageTo', '$username', '$messageBody')";
if(mysql_query($query))
echo "done.";
else
echo "Problem with Query";
}
Column names should be in single inverted commas
You should check for the mysql_query to give success response.
do not call the same function again and again i.e mysql_real_escape_string was called 2 times for the same thing. Alternatively assign that to a variable, although you need not have escaped the values to check in if condition

linking and sending form values to mysql database?

My html code:
<form action="send_post.php" method="post">
<input type="submit" value="Login" />
</form>
PHP code:
<?php
$con = mysqli_connect("","","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{
// echo('Connected with Mysql');
}
#mysql_select_db("a", $con);// connect to database db_name
if (isset($_POST['Submit']))
{
$email=$_POST['email'];
$pass=$_POST['pass'];
$sql_query="INSERT INTO formdata (email, pass) VALUES('$email', '$pass')";}
?>
Database name: mysql
Table name: formdata
Why it is not working? in second line I used 'local host' first but I was receiving error so I removed it.
You use the mysqli_ API to connect to your database and then test for errors and try to select a database with the mysql_ API. Pick one and stick to it. (Don't pick mysql_ it is deprecated).
You only run the form handling code if there is a Submit data item in the submitted data. You have no form control with name="Submit" so that will never happen.
Your form handling code expects there to be email and pass data in the submitted data but your form does not have fields with those names.
Constructing an SQL query as a string and storing it in a variable is insufficient to do anything to your database. You have to actually sent it to the database server. That would use mysqli_query with your current approach, but you should switch to prepared statements

Error with simple PHP form with MySQL

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

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

Categories