简体   繁体   English

使用PHP将数据插入两个单独的表中

[英]Inserting data into two separate tables using PHP

I am trying to insert data into two different tables in the same database, if I try to insert it into one database, it works, however, once I insert the second query into my code ( $desc_query ) it won't update any table. 我正在尝试将数据插入同一数据库中的两个不同表中,如果尝试将其插入一个数据库中,则可以正常工作,但是,一旦将第二个查询插入我的代码( $desc_query )中,它将不会更新任何表。

Here is my code: 这是我的代码:

    $name= strip_tags($_POST['name']);
    $l_name= strip_tags($_POST['last_name']);

    $c_id = strip_tags($_POST['company_id']);
    $a_d = strip_tags($_POST['add_description']);
    $d_t = strip_tags($_POST['desc_text']);

$connect = mysql_connect('localhost','id','pass') or die ("couldn't connect!"); 

mysql_select_db('database_db') or die('could not connect to database!');   

//inserting names

$job_query=mysql_query("INSERT INTO names VALUES ('', '$name', '$l_name')");

    //inserting a new description if needed. (this is the part that ruins everything)
if($a_d == 'true'){
    $desc_query=mysql_query("INSERT INTO descriptions VALUES ('','$c_id','$d_t')");
}

You might be having an issue where some characters (like ' and ") are breaking the SQL query (not to mention opening your application up for SQL injection attacks). 您可能遇到一个问题,其中某些字符(例如'和“)破坏了SQL查询(更不用说为SQL注入攻击打开应用程序了)。

I would recommend sanitizing all user provided data like so: 我建议清理所有用户提供的数据,如下所示:

$name = mysql_real_escape_string(strip_tags($_POST['name']), $connect);
$l_name = mysql_real_escape_string(strip_tags($_POST['last_name']), $connect);
...
$d_t = mysql_real_escape_string(strip_tags($_POST['desc_text']), $connect);

Always operate under the assumption that the user is going to enter something outlandish or malicious that may (or may not) break your SQL. 始终在用户将要输入可能会(或可能不会)破坏您的SQL的古怪或恶意内容的假设下进行操作。

Have you tried to echo out the queries and then to run them directly on the database? 您是否尝试回显查询,然后直接在数据库上运行它们?

Without any more information about the database we can't really tell if the queries themselves are valid. 如果没有有关数据库的更多信息,我们将无法真正确定查询本身是否有效。

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

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