简体   繁体   中英

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.

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).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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