使用PHP向MySQL插入数据和插入多条数据
作者:野牛程序员:2023-11-13 22:51:02php阅读 2418
向MySQL插入数据可以使用PHP的MySQLi或PDO扩展。以下是使用MySQLi插入单条数据和多条数据的示例:
插入单条数据
<?php $servername = "your_servername"; $username = "your_username"; $password = "your_password"; $dbname = "your_dbname"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 要插入的数据 $data_to_insert = "INSERT INTO your_table_name (column1, column2, column3) VALUES ('value1', 'value2', 'value3')"; // 执行插入 if ($conn->query($data_to_insert) === TRUE) { echo "数据插入成功"; } else { echo "Error: " . $data_to_insert . "<br>" . $conn->error; } // 关闭连接 $conn->close(); ?>
插入多条数据
<?php $servername = "your_servername"; $username = "your_username"; $password = "your_password"; $dbname = "your_dbname"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 要插入的多条数据 $data_to_insert = "INSERT INTO your_table_name (column1, column2, column3) VALUES ('value1', 'value2', 'value3'), ('value4', 'value5', 'value6'), ('value7', 'value8', 'value9')"; // 执行插入 if ($conn->query($data_to_insert) === TRUE) { echo "数据插入成功"; } else { echo "Error: " . $data_to_insert . "<br>" . $conn->error; } // 关闭连接 $conn->close(); ?>
请注意替换代码中的"your_servername"、"your_username"、"your_password"、"your_dbname"、"your_table_name"、"column1"、"column2"、"column3"、"value1"等信息为实际的数据库连接信息和数据。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
- 上一篇:mysql数据库命令大全
- 下一篇:php如何向input输入框写入数值