problem in database connection

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
samratbabu
Forum Newbie
Posts: 3
Joined: Thu Oct 16, 2008 5:35 am

problem in database connection

Post 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.........
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: problem in database connection

Post by papa »

Look in your php.ini file if error_reporting is on.

You have synthax error in that code.
samratbabu
Forum Newbie
Posts: 3
Joined: Thu Oct 16, 2008 5:35 am

Re: problem in database connection

Post by samratbabu »

yeh, error_reporting is on
can you tell where the error is located?
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: problem in database connection

Post by papa »

mysql_close($con)
?>

Should be

Code: Select all

 
mysql_close($con);
?>
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: problem in database connection

Post 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.
Post Reply