Page 1 of 1

problem in database connection

Posted: Fri Oct 17, 2008 2:49 am
by samratbabu
Hello Friend
i am very new in php world.pls help me.
i want to coonect mysql database through follwoing code
<?php

$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("test", $con);

$sql="INSERT INTO example (id, data)
VALUES('$_POST[txtId]','$_POST[txtData]')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>

when i am executing it through debugging it work perfectly. but if i run it in browser id does not work, even not show any message. how can i over it?

thanks.........

Re: problem in database connection

Posted: Fri Oct 17, 2008 3:06 am
by papa
Look in your php.ini file if error_reporting is on.

You have synthax error in that code.

Re: problem in database connection

Posted: Fri Oct 17, 2008 3:17 am
by samratbabu
yeh, error_reporting is on
can you tell where the error is located?

Re: problem in database connection

Posted: Fri Oct 17, 2008 3:22 am
by papa
mysql_close($con)
?>

Should be

Code: Select all

 
mysql_close($con);
?>

Re: problem in database connection

Posted: Fri Oct 17, 2008 5:38 pm
by califdon
Since you are just starting to use PHP, I will make a couple of comments:

When you have a PHP syntax error anywhere in your script, PHP will usually not send anything to Apache to send to the browser, resulting in a completely blank page, unless you have some HTML outside the PHP tags. You can use this knowledge to spot a simple syntax error, such as the missing semicolon that papa pointed out for you. Whenever you get no PHP output, always look for a syntax error.

You don't need all the complex if statements to trap MySQL connection problems. The normal syntax is like this:

Code: Select all

$con = mysql_connect("localhost","username","password") or die('Could not connect: ' . mysql_error());
If you post php code in this forum in the future, please enclose it between the special BBCode tags [ php] and [ /php] (without the spaces I added here so they won't be parsed). This helps a lot in reading your code.