Click to See Complete Forum and Search --> : [RESOLVED] NEWBIE - Insert does not work


Phibermaster
03-04-2008, 03:52 PM
Hi, i am just learning php and mysql and am trying to insert a value into my database. The full script is below. The connection etc is working but when i check the database no record gets inserted even though the php-script does not return any warnings...What simple thing am i doing wrong.

<?php
include('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());

$sql = "INSERT INTO assessment (age) VALUES('35')";

$result = mysql_query($sql);
if (!$result)
{
die ("Could not insert the database: <br />". mysql_error());
}

}


?>

Yelgnidroc
03-04-2008, 04:46 PM
You probably don't need quotes around the 35

$sql = "INSERT INTO assessment (age) VALUES('35')";

Phibermaster
03-04-2008, 04:56 PM
removed the quotes, but it still dont work.

Yelgnidroc
03-04-2008, 05:41 PM
Try to echo $sql then paste this into the phpMyAdmin SQL

chazzy
03-04-2008, 06:05 PM
It looks like your entire block of code is wrapped in a big if.

I fixed your formatting error, try this.


<?php
include('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());
} else {
$sql = "INSERT INTO assessment (age) VALUES('35')";

$result = mysql_query($sql);
if (!$result)
{
die ("Could not insert the database: <br />". mysql_error());
}

}
?>

Nedals
03-04-2008, 10:00 PM
As chazzy points out, you had your INSERT in the wrong block.
Get into the habbit of indenting blocks and be consistant on where you put your open, {, and close, } braces. You don't really need the 'else' in chazzy's example but it won't do any harm.
Life will be so much easier. :)

<?php
include('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());
}
$sql = "INSERT INTO assessment (age) VALUES('35')";
$result = mysql_query($sql);
if (!$result) {
die ("Could not insert the database: <br />". mysql_error());
}
?>

Phibermaster
03-05-2008, 04:49 PM
Thanks alot!! It is working fine now. I really appreciate your help. I will definitely be more careful with how i indent the code...:-))