简体   繁体   中英

SQL Query works in SQL but not in PHP

I have a relational insert which works like a charm in mysql, but when I put in into a query in PHP, nothin' doin'. Can someone help?

        $qry = "
            INSERT into orders
                ( customerid, date, order_status ) 
            VALUES 
                ( '$customerid', '$date', $order_status );
            INSERT into order_items
                ( orderid, isbn, item_price, quantity )
            VALUES
                ( LAST_INSERT_ID(), '12345', 5, 1 )
        ";

when I remove the second insert, it works as advertised in PHP. I am running EasyPHP5.3. Thanks!

Unless you are using mysqli_multi_query() you cannot run more than one query at a time in PHP. So you'll need to break that query into two queries or use the previously mentioned function.

Hope this work for you

        $qry = "
        INSERT into orders
            ( customerid, date, order_status ) 
        VALUES 
            ( '$customerid', '$date', $order_status )";

        $qry.=" INSERT into order_items
            ( orderid, isbn, item_price, quantity )
        VALUES
            ( LAST_INSERT_ID(), '12345', 5, 1 )
    ";   

    $mysqli->multi_query($query)       

OK, so SQL and PHP may have some common grounds but they still have differences.

If you want to perform multiple queries, at time it might result into an error in PHP because PHP needs to send a request to SQL before it executes the query and one request is to one query. (I think meehee).

If you were to transfer your code to PHP this is the code, I guess you already know how to setup a connection between your php file and your database right, if not feel free to ask or update your question. But this is how to do your code in PHP:

<?php
$sqlOrders = "INSERT INTO orders (customer_id, date, order_status)
VALUES
('$customer_id','$date','$customer_status')";

$sqlOrderItems = "INSERT INTO order_items (orderid, isbn, item_price, quantity)
VALUES
(LAST_INSERT_ID(), '12345', 5, 1)";

After that you need to call this command for this is the request.

if(!mysqli_query($link <--- connection to your database,$sqlOrders)){
die('Error: ' . mysqli_error($link));
}

if(!mysqli_query($link,$sqlOrderItems)){
die('Error: ' . mysqli_error($link));
}
?>

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