Get and insert Data into MySQL database using PHP

2019-06-06 11:11发布

问题:

I have managed to connect to database and I manage to insert using following code.

<?php

$username = 'root';
$password = '';
$db = 'demo';

$conn = new mysqli ('localhost',$username, $password, $db) or die("unable to connect");

$sql="insert into persons (first_name,last_name,email_address) values ('sara','smith','email@email.com')";
$query=mysqli_query($conn,$sql);
if($query)
    echo 'data inserted';
?>

But the problem is that when I try to enter data using HTML form, it didn't work for me. I have tried to follow different tutorials and different answers here on stackoverflow. Can anyone please tell me the easiest way of inserting and getting data from MySQL using PHP ?

If there is any easy tutorial or blog from where i can learn and understand all this, I would love to watch or read.

回答1:

I manage to do it in following way.

Create a file name index.php with following code

<!DOCTYPE html>
<html lang="en">    
<head>
<meta charset="UTF-8">    
<title>Add Record Form</title>
</head>

<body>
<form action="insert.php" method="post">

    <p>
        <label for="firstName">First Name:</label>
        <input type="text" name="firstname" id="firstName">    
    </p>

    <p>
        <label for="lastName">Last Name:</label>
        <input type="text" name="lastname" id="lastName">    
    </p>

    <p>    
        <label for="emailAddress">Email Address:</label>
        <input type="text" name="email" id="emailAddress">    
    </p>

    <input type="submit" value="Submit">
</form>
</body>
</html>

Then create another file name as insert.php

<?php

    /* Attempt MySQL server connection. Assuming you are running MySQL
    server with default setting (user 'root' with no password) */

    $link = mysqli_connect("localhost", "root", "", "demo");

    // Check connection

    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    // Escape user inputs for security
    $first_name = mysqli_real_escape_string($link, $_POST['firstname']);
    $last_name = mysqli_real_escape_string($link, $_POST['lastname']);
    $email_address = mysqli_real_escape_string($link, $_POST['email']);

    // attempt insert query execution
    $sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";

    if(mysqli_query($link, $sql)){
        echo "Records added successfully.";
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }

    // close connection
    mysqli_close($link);
?>


回答2:

//procedural style

$mysqli =  mysqli_connect('host','username','password','database_name');

//Output any connection error

if ($mysqli->connect_error) {

die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);

}

//inserting a record

$product_code = '"'.$mysqli->real_escape_string('P1234').'"';
$product_name = '"'.$mysqli->real_escape_string('42 inch TV').'"';
$product_price = '"'.$mysqli->real_escape_string('600').'"';

//MySqli Insert Query

$insert_row = $mysqli->query("INSERT INTO products (product_code, product_name, price) VALUES($product_code, $product_name, $product_price)");

if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />'; 
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}


回答3:

A quick and untested example of using an HTML form with the POST method to insert data entered by a user into the db.

<?php

    $result = false;

    $dbhost = 'localhost';
    $username = 'root';
    $password = '';
    $db = 'demo';

    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        $conn = new mysqli ( $dbhost,$username, $password, $db );
        if( $conn ){

            $sql='insert into `persons` ( `first_name`,`last_name`,`email_address` ) values (?,?,?);';
            $stmt=$conn->prepare( $sql );
            $stmt->bind_param('sss', $_POST['firstname'], $_POST['lastname'], $_POST['email'] );
            $result = $stmt->execute();

        }
        $conn->close();
    }

?>
<!doctype html>
<html>
    <head>
        <title>Simple Form submission example</title>
    </head>
    <body>
        <form method='post'>
            <input type='text' name='firstname' />
            <input type='text' name='lastname' />
            <input type='text' name='email' />

            <input type='submit' value='Submit' />

            <?php
                echo $result ? '<div>The database was updated</div>' : '';
            ?>
        </form>
    </body>
</html>


回答4:

Try tutsplus or lynda, Provide you with the best tuto !