...

View Full Version : newbie simple qry - Adding a record to a db via php



obaluba
02-01-2007, 11:15 AM
Another simple one (I hope)

I'm still learning PHP, I've managed to view the records in my mysql db but i cant seem to add a record, ive made a basic html form, which all checks out, along with this php file:

<?
$dbhost='localhost';
$user='cdesi_admin';
$password='abcd';
$database='cdesi_contacts';

/* $dbh=mysql_connect ("localhost", "cdesi_admin", "abcd") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("cdesi_contacts");
*/

$first=$_POST['first'];
$last=$_POST['last'];
$phone=$_POST['phone'];
$mobille=$_POST['mobille'];
$fax=$_POST['fax'];
$email=$_POST['email'];
$web=$_POST['web'];

mysql_connect($dbhost,$user,$password);
@mysql_select_db($database) or die("Unable to Select Database");

mysql_query($query);

/* $query = "INSERT INTO cdesi_contacts VALUES ('first', 'last', 'phone', 'mobille', 'fax', 'email', 'web')"; */

$query = "INSERT INTO `contacts` VALUES ( `id` , `first` , `last` , `phone` , `mobille` , `fax` , `email` , `web` )";

mysql_close();
?>

when I run this, it just gives me a blank page with no errors, however the database doesnt update? I'm not sure what I'm doing wrong.

The database is called contacts as is the table and ive got a user login which gives me full access

any help would be really appreciated!

thanks :)

raf
02-01-2007, 11:56 AM
you're first executing the query, and then building it ...

mysql_query($query);

should come after

$query = "INSERT INTO `contacts` VALUES ( `id` , `first` , `last` , `phone` , `mobille` , `fax` , `email` , `web` )";

obaluba
02-01-2007, 12:06 PM
thanks for that raf, ive changed that now, but im still getting the same white page once the php has run, yet the database isnt updated

I built the db with phpmyadmin, its only simple, is there anything i might have missed out which would explain why this wont update

thanks for your reply :)

raf
02-01-2007, 12:26 PM
don't get m wrong, but you should take up a good book/tutorial/etc so you learn from the start on to write easy to debug code.

if you're doing inserts, you should have at least some additional checks/debug like


mysql_query($query) or die('Queryproblem insert. Executed statement: '. $query . ' <br />generated the following error: '. mysql_error());
if (mysql_affected_rows() != 1){
echo mysql_affected_rows(), ' rows inserted, when it should have been 1';
}


this will probably tell you that your values are invalid --> a backtick ( `)is not the same as a single quote ( ' ) and 'id' looks like a strange value to me. I'd recon you're confusing the fieldlist with the valuelist...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum