简体   繁体   English

简单的 php - mysql 选择和插入

[英]Simple php - mysql select and insert

I am not a programmer (duh), I just need to make a really simple tool for populating sql database.我不是程序员(废话),我只需要制作一个非常简单的工具来填充 sql 数据库。 First I have html with form:首先我有表单的html:

<form action="http://localhost:8081/phpSearch.php" method ="post">
Enter code: <input type="text" name="search"><br>
<input type ="submit">
</form>

and then php that should connect to MYSQL, search for data according to input (code,name) in one table and then populate another table with the result.然后应该连接到MYSQL的php,根据一个表中的输入(代码,名称)搜索数据,然后用结果填充另一个表。 And I'm only mising what to put instead of question marks.我只是想念放什么而不是问号。

<?php
$search1 = $_POST['search'];

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";

$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT code,name FROM users WHERE code LIKE '%$search1%'";

$sql2 = "INSERT INTO newUsers (newCode,newName) VALUES ('$search1', ??????)";

$conn->close();
?>

I'm pretty sure this is easy for you experts, so thanks in advance.我很确定这对您的专家来说很容易,所以提前致谢。

You could actually do this in a single SQL query:您实际上可以在单个 SQL 查询中执行此操作:

$search1 = "%".$_POST['search']."%";
$sql = "INSERT INTO newUsers (newCode, newName) SELECT code, name FROM users WHERE code LIKE ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $search1);
$stmt->execute();

This will insert all the results of the SELECT query directly into the other table, without needing any intermediate processing in PHP.这会将 SELECT 查询的所有结果直接插入到另一个表中,无需在 PHP 中进行任何中间处理。 More about the INSERT...SELECT query format can be found here .可以在此处找到有关INSERT...SELECT查询格式的更多信息。

Note I've used prepared statements and parameters - which both executes the query securely and reduces the risk of accidental syntax errors.注意我使用了准备好的语句和参数——它们既安全地执行查询又降低了意外语法错误的风险。 You can get more examples of this here .您可以在此处获得更多示例。

Also, in a real application you shouldn't log in as root from your web application - instead create a SQL account for the application which has only the privileges it actually needs .此外,在实际应用程序中,您不应以 root 身份从 Web 应用程序登录 - 而是为该应用程序创建一个 SQL 帐户,该帐户仅具有它实际需要的权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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