简体   繁体   中英

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.

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.

$ins="insert into Student (`id`,`fname`,`lname`,`address`,`city`,`state`,`zip`,`phone`,`email`,`books`,`comments`)values
  ('".$ID."','".$fname."','".$lname."','".$address."','".$city."','".$state."','".$zip."','".$phone."','".$email."','".$books."','".$comments."')"; 

mysql_query($ins); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM