在本地主机上使用带有 xampp 的 PHP 获取数据并将其插入 MySQL 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38812682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:44:02  来源:igfitidea点击:

Get and insert Data into MySQL database using PHP with xampp on localhost

phpmysqldatabasemysqli

提问by Malik

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 protected]')";
$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 ?

但问题是,当我尝试使用 HTML 表单输入数据时,它对我不起作用。我试图在stackoverflow上遵循不同的教程和不同的答案。谁能告诉我使用 PHP 从 MySQL 插入和获取数据的最简单方法吗?

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

如果有任何简单的教程或博客可以让我学习和理解所有这些,我很乐意观看或阅读。

回答by Malik

I manage to do it in following way.

我设法通过以下方式做到这一点。

Create a file name index.php with following code

使用以下代码创建文件名 index.php

<!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

然后创建另一个文件名作为 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);
?>

回答by Saurav Suman

//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

//MySqli插入查询

$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);
}

回答by RamRaider

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

使用带有 POST 方法的 HTML 表单将用户输入的数据插入数据库的快速且未经测试的示例。

<?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>

回答by BOUKANDOURA Mhamed

Try tutsplusor lynda, Provide you with the best tuto !

试试tutspluslynda,为您提供最好的 tuto!