Connection Problems

Hello,

I am new to php and any help would be appreciated. I have a simple connection script I wrote for php to put data into a mysql database. I got it to work once, but when I refresh the browser to try it again, I get an error. What am I doing wrong? Here’s the code:

html doc:

<?php include("connec.php"); ?> Hello username:
password:

Here is the connection file:

<?php $db_host = 'localhost'; $db_user = 'root'; $db_pass = 'root'; $dbc = mysql_connect($db_host,$db_user,$db_pass); if(!$dbc){ die("No Server!"); } echo "
"; $dbase = mysql_select_db("testing", $dbc); if(!$dbase){ die("No Database!"); } $value = $_POST['username']; $value1 = $_POST['password']; $sql = "INSERT INTO login (username, password) VALUES ('$value', '$value1')"; if(!mysql_query($sql)){ die("No Tables!"); } mysql_close(); ?>

I got it to work once but when I refresh the browser, I get an error. It got it to work again When I emptied the database. Strange…

Any help would be appreciated.

I’m using a Macbook Pro and mamp.

Before using $_POST, $_GET, $_COOKIE, $_SESSION or $_REQUEST data, you should check that it is set, with the isset function:

[php]$value = $_POST[‘username’];
$value1 = $_POST[‘password’];

$sql = “INSERT INTO login (username, password) VALUES (’$value’, ‘$value1’)”;

if(!mysql_query($sql)){
die(“No Tables!”);
}[/php]

Becomes:

[php]if(isset($_POST[‘username’]) && isset($_POST[‘password’])) {
$value = $_POST[‘username’];
$value1 = $_POST[‘password’];

$sql = "INSERT INTO login (username, password) VALUES ('$value', '$value1')";

if(!mysql_query($sql)){
    die("No Tables!");
}

}[/php]

Also, which error do you get?

I’m getting the error “No Fields!” I created for testing purposes. Everything works except for inserting thing into the database. It worked the first time and it works when I empty the mysql database. I’m curious, what does the “isset” use for?

Thanks for your help.

Does it still not work with the isset?

isset checks whether a variable exists. When you’re accepting user input, it may not have been sent (e.g. if the page has just been viewed without the form being submitted).

I haven’t tried yet but I will. It looks like you have an if statement first to use isset?

It Worked! Thanks you’re Awesome! Why didn’t mine code work? If you have time to explain.

If the MySQL query failed (returning FALSE), then it would give the error message you had. It’s probably because you tried to insert a blank record (as the form had not been filled). Some MySQL table items will not allow a NULL or blank entry.

That was exactly what was happening. When I would refresh the screen sometimes, I would go back and check the database and a blank record would be in there. When you sent me the first and second response, It started making sense. I see why you’re an expert.

Thanks a million.

Sponsor our Newsletter | Privacy Policy | Terms of Service