Inserting data into a mysql database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gerrymac
Forum Newbie
Posts: 15
Joined: Sat Mar 13, 2004 6:19 am

Inserting data into a mysql database

Post by gerrymac »

Hi

i ma currently trying to insert data into a database but all i seem to be doing is inserting blank rows of data. here is my code for both the form and the PHP script

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>


<p>Personal Insert New Entry</p>
<form name="form1" method="post" action="insert_per3.php">
<p>firstname
<input type ="text" name= "firstname">
</p>
<p>lastname
<input type ="text" name= "lastname">
</p>
<p>
<input type="submit" name="Submit" value="add new record">
</p>
</form>
<p>&nbsp;</p>


</body>
</html>


// php code
<?php

if(empty($_POST["firstname"]))
{
echo "Please go back and enter your first name";
}





if(empty($_POST["lastname"]))
{
echo "Please go back and enter your last name";
}



$connection=mysql_connect("localhost","root","");


if (!$connection)
{
echo "Could not connect to MySQL server!";
exit;
}

$db=mysql_select_db("test2",$connection);

if (!$db)
{
echo "Could not change into the database";
exit;
}



$query = "insert into per2 (firstname, lastname) values('".$firstname."','".$lastname."')";

mysql_query($query);


?>

can anyone shed some light on why this is happening. (global variables are set to off)

any help wpuld be greatly appreciated
Gerry
TheBentinel.com
Forum Contributor
Posts: 282
Joined: Wed Mar 10, 2004 1:52 pm
Location: Columbus, Ohio

Re: Inserting data into a mysql database

Post by TheBentinel.com »

gerrymac wrote: $query = "insert into per2 (firstname, lastname) values('".$firstname."','".$lastname."')";

can anyone shed some light on why this is happening. (global variables are set to off)
It'd be worth your time to print the values of firstname and lastname so you can see if they are populated.

print ("<HR>" . $firstname . "<HR>" . $lastname . "<HR>");

With globals off, do you have to use $_REQUEST["firstname"] to get at the values?
evilcoder
Forum Contributor
Posts: 345
Joined: Tue Dec 17, 2002 5:37 am
Location: Sydney, Australia

Post by evilcoder »

try this:

Code: Select all

$Prequery = "INSERT INTO per2
                    SET firstname = '$firstname' , lastname = '$lastname'";
$Query = mysql_escape_string ( $Prequery );
$Insert = mysql_query ( $Query );
mysql_escape_string is just to stop people from Injecting malicious SQL into your database. The rest is just changing the way you put values into the database, can be good to use this method to iron out problems.
Post Reply