PDA

Click to See Complete Forum and Search --> : SQL Hidden Problem


Brendan
Mar 15th, 2005, 06:37 AM
Right. This script just adds some information into a database. The information comes from text-boxes. My problem is that, when everything works until I hit the Submit button. The entries in the text-boxes disappear and nothing happens. I wrote a viewing script to check and see if the values were actually entered into the database, but no such luck. Any idea what I'm doing wrong?


<?php

if ($_POST['submit'])
{
//connect to mysql
$connect = mysql_connect('localhost','username','password');
//verify connection
if (!$connect)
{
echo 'Unable to connect to MySQL<br>' . mysql_error() . '';
}

//select a database
$select = mysql_select_db('database');
//verify db selection
if (!$select)
{
echo 'Unable to select a database<br>' . mysql_error() . '';
}

//get values
//to be inserted into database
$title = $_POST["title"];
$author = $_POST["author"];
$message = $_POST["message"];
$tdate = $_POST['tdate'];

//add values into database
//add them in the corresponding fields
$query = "INSERT INTO news (id,title,author,message,tdate)" . "VALUES ('NULL','$title','$author','$message','$tdate')";
$r_query = mysql_query($query);
//veryify query
if ($r_query)
{
echo 'Query has been completed.';
}
}
else
{
?>

<form method="post" action="sql_add.php">
<table>
<tr>
<td>Title:</td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td>Author:</td>
<td><input type="text" name="author"></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" name="tdate"></td>
</tr>
<tr>
<td>Message:</td>
<td><input type="text" name="message"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>

<?php
}
?>


Thanks ahead of time,
--Brendan :p

KTottE
Mar 15th, 2005, 07:00 AM
Is the id-field in the database a varchar type or an integer type? Why are you including it there if you're just going to plonk 'NULL' into it?

visualAd
Mar 15th, 2005, 07:15 AM
KTotte is right. You can omit the ID from your field list if the database is gernetating it automatically.

The reason your form isn't working is because you are not checking the submit variable properly. If the user submits the form then the variable $_POST['name'] is created and set to a null string ''. If the form is not submitted then the $_POST['name'] variable is not created at all. In both cases testing for the variable with an IF statement will return false, as a null string is evaluated as a false.

Instead use the isset() (http://www.php.net/isset) function to test whether or not the variable was actually created:

if (isset($_POST['submit']))

Brendan
Mar 15th, 2005, 01:34 PM
Thanks for the help you guys.

As for the SQL thingy, I'm just starting to learn SQL (or relearn it rather) and I based that code of off a tutorial I read. The tutorial used NULL for the ID field - but if it's not needed, that's still fine.

Thanks again!
--Brendan :p