Deena Deena - 2 years ago 97
PHP Question

Data not entered into database from PHP

I am trying to enter data into a database with PHP.

Here is my code:

<?php
$username = 'username'; //username for database
$password = 'password'; //password for database
$hostname = 'localhost'; //host
$db_name = 'db_testdrubin'; //name of database

$db_selected = mysqli_connect($hostname, $username, $password, $db_name)//specify database
or die ("unable to connect");

if(isset ($_POST['submit'])){
$ID = ($_POST['ID']);
$fname = ($_POST['fname']);
$lname = ($_POST['lname']);
$address = ($_POST['address']);
$city = ($_POST['city']);
$state = ($_POST['state']);
$zip = ($_POST['zip']);
$phone = ($_POST['phone']);
$email = ($_POST['email']);
$books = ($_POST['books[]']);
$comments = ($_POST['comments']);
}
else{
echo'<p>not submitted</p>';
}
//up until this point the code works fine

$query = 'INSERT INTO Student VALUES ($ID, $fname, $lname, $address, $city, $state, $zip, $phone, $email, $books, $comments)';


$success = $db_selected->query($query);

if($success){
$count = $db_selected->affectd_rows;
echo '<p>$count were added</p>';
}
else{
echo '<p>error</p>';
}

?>


I know that the information is being read from the html form correctly because I have checked by printing the individual variables. I am not getting any error messages when I submit the form, just the "error" echo statement from the if/else statement, and no data is entered into the database.

I have also tried this:

if (!mysql_query($db_selected, $query)){
echo '<p>error</p>';
}


with the same results.

Answer Source

Change this

$query = 'INSERT INTO Student VALUES ($ID, $fname, $lname, $address, $city, $state, $zip, $phone, $email, $books, $comments)';

to

$query = "INSERT INTO Student VALUES ($ID, '$fname', '$lname', '$address', '$city', '$state', $zip, $phone, '$email', '$books', '$comments')";

I mean to say if its string then do like '$string' and also use

$db_selected->real_escape_string($stringval);

and use

echo $db_selected->error;

to check the error you got.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download