SQL Query works in SQL but not in PHP - 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));
}
?>

Related

SQL query will fail with actual data but will work with test data

So, im trying insert some data into a table, I get the previous data from either GET or another SQL query (My database consists of INT and TEXT so I don't think there is an issue there).
I have a query
$sql2 = "INSERT INTO orders (USER_NAME, USER_ID, ARTIST_ID, ARTIST_NAME, PRICE, DESCRIPTION, COMMENTS)
VALUES ('$user_name','$user_id','$artist_id','$artist_name','$price','$description','$comments')";
This $sql2 echo's as follows
INSERT INTO orders (USER_NAME, USER_ID, ARTIST_ID, ARTIST_NAME, PRICE, DESCRIPTION, COMMENTS) VALUES ('myname','1',''1'','Actual Name','19.99','test','tst2')
However, when I do
if ($conn->query($sql2) === TRUE) {
$conn->close();
echo "success";
exit();
} else {
$conn->close();
echo "failed";
}
I get failed printed. But if I change the $sql2 into
VALUES ('test','test','test','test','test','test','test')";
The query is executed successfully inserted into my database (other than the int values that turn into 0). Could someone enlighten me why this would happen?
for some reason your artist_id value has a double quotation mark while other values has single quotation mark, which is probably the reason your query fails( i have bolded it):
INSERT INTO orders (USER_NAME, USER_ID, ARTIST_ID, ARTIST_NAME, PRICE, DESCRIPTION, COMMENTS) VALUES ('myname','1',''1'','Actual Name','19.99','test','tst2')

is it possible to execute 2 query at the same time?

hey guys i have this problem..
basicly the first query is jsut for inserting and the 2nd query is for copying data from another table via foreign key. have any idea? im newbie.. :D
else if($payment_description == 'Monthly Subscription'){
$payment_amount = '750';
$sql = "INSERT INTO `paymentlog` ( payment_amount,payment_description,date_payment)
VALUES ( '$payment_amount', '$payment_description','$date_payment')";
$query_run = mysqli_query($conn, $sql);
$sql1 = "INSERT INTO paymentlog (member_id, first_name, last_name)
SELECT member_id, first_name, last_name
FROM member
WHERE member_id = $id";
$query_run1 = mysqli_query($conn, $sql1);
echo ("<script LANGUAGE='JavaScript'>
window.alert('Monthly Payment is been added.');
window.location.href='/PROJECT/MEMBERS/members.php';
</script>");}
I don't think your current code does what you want. You are (attempting to) insert two rows, while, as I understand your question, you want to create a single row in payment_log, with the amount, description and date given as input, and member information that needs to be retrieved from another table using another input paramter.
You can use the insert ... select syntax:
INSERT INTO `paymentlog` (
member_id,
first_name,
last_name,
payment_amount,
payment_description,
date_payment
)
SELECT
member_id,
first_name,
last_name,
:payment_amount,
:payment_description,
:date_payment
FROM member
WHERE member_id = :id
Important notes:
Use prepared statements! Do not concatenate variables in the query string, this is both inefficient and unsafe. Recommended reading: How can I prevent SQL injection in PHP
From a database design standpoint, you should not be duplicating information from table members in table payment_log; storing a reference to the primary key of member is sufficient

Can I add different data to two different tables using separate INSERT statements within nested IF statements?

I have a system where someone can place and order for multiple products, the same or different. I am storing some of the cart data (an overview of the order) to an orders table and I want to store specific item data to another table, order_item (eg quantity, product_id etc). The first query to INSERT INTO orders is working, but somehow, the second query won't INSERT INTO the second table. In order to insert into the second table, I need to find the highest id number from the orders table as well, so that this can be added to the order_item table.
Here are the SQL statements:
if(empty($hNum) || empty($street) || empty($city) || empty($county) || empty($postcode) || empty($country)){
header("Location: ../shop/checkout.php?error=emptyaddressfields");
exit();
}
else {
$sqlO = "INSERT INTO orders (customer_id, order_date, order_status, num_items, total_cost)
VALUES ('$customer_id', CURRENT_TIMESTAMP, 'Order Placed', '$num_items', '$total_cost')";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sqlO)) {
header("Location: ../shop/checkout.php?error=sqlerror");
exit();
}
else { //if statement here for second sql insert
$sqlMaxId = "SELECT order_id FROM orders ORDER BY order_id DESC LIMIT 1";
$sqlOI = "INSERT INTO order_item (order_id, product_id, quantity)
VALUES ('$sqlMaxId', '$productID', '$productQty')";
$result = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($result, $sqlOI)) {
header("Location: ../shop/checkout.php?error=sqlerror3");
}
else {
mysqli_stmt_execute($stmt);
unset($_SESSION['shopping_cart']);
header("Location: ../shop/account.php");
exit();
}
}
}
All of the variables are named correctly, but there's no point putting them here. Maybe worth mentioning that all the variables are being taken via $_POST from another page where a form is submitted.
For finding the max id number, I have tried using MAX(id) but doesn't seem to work, maybe it's because the whole statement isn't working properly, but this definitely will work.
I think it could be a problem with how the statements are nested?
Any help would be appreciated!
$sqlMaxId = "SELECT order_id FROM orders ORDER BY order_id DESC LIMIT 1";
$sqlOI = "INSERT INTO order_item (order_id, product_id, quantity)
VALUES ('$sqlMaxId', '$productID', '$productQty')";
Here you are inserting the actual string $sqlMaxID
Even if you did like the below so the variable contents would be included, $sqlMaxId represents the String "select ..." and not the results of that query.
$sqlOI = "INSERT INTO order_item (order_id, product_id, quantity)
VALUES (" $sqlMaxId "," $productID "," $productQty ")";
Nested Ifs == the Devil. Also this needs to be done in one transaction. What would happen if two customers submit at the same time and by the time the second sql statement runs, the max ID has changed to the next customer?
What you should do is create a stored procedure that will handle all of the insert logic. Your application should not know or care about how the data is organized in the database. So in your new stored procedure you can use the Output Clause to output the data you just inserted into table 1 (including the identity column) into a table variable that will contain only what was successfully inserted. You can then join to that table variable to get the ID you want for the second insert. The output clause looks like this:
DECLARE #NewItem Table(ItemID int)
insert into Table1(Some stuff)
OUTPUT Inserted.ID
INTO #NewIssue
Values(1,2,3, etc)

Why do I get a 500 error? (MySQL php)

<html>
<head>
HTML CODE
<?
$username="xxxxxx";
$password="xxxxxx";
$database="xxxxxx";
mysql_connect(localhost,$username,$password);
$escape = "INSERT INTO monster VALUES ('',$_POST["name"],$_POST["soort"])";
$escape2 = "DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL";
$query=mysql_real_escape_string($escape);
$query2=mysql_real_escape_string($escape2);
#mysql_select_db($database) or die("MySQL error: Kan inte ansluta till databasen.");
mysql_close();
?>
</body>
</html>
Every time i run this(from another file, containing the name and soort post's) I get an 500 internal server error. First I figured that the queries may be the problem, but they don't even get executed. However, i tried to escape the queries. But still error.
What is wrong with this code? (note: $escape2 is some code i found that removes duplicates in the database. But i don't really know how to format it so that it can be used through php.)
Use something like below...
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Please do not insert values without escaping.
problem in insert into statement
it should be
$escape = "INSERT INTO monster VALUES ('',".$_POST['name'].",".$_POST['soort'].")";
it is preferable to write colums name while writing insert queries
if column contains string values like VARCHAR or TEXT then use quoted_printable_decode
pass null if column is autoincrement
insert statment
$escape = "INSERT INTO monster (col1, col2, col3) VALUES (NULL,'".$_POST['name']."',".$_POST['soort'].")";
or
$escape = "INSERT INTO monster (col2, col3) VALUES ('".$_POST['name']."',".$_POST['soort'].")";
It looks like you need something like this:
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Also I would suggest to use prepared statements because it is bad experience to build queries.
First of all I have cool proposition for you. What do you say about some advanced PHP? One step further into great world of safe PHP + MySQL apps?
Introducting to you a PDO. (I know this is not answer to your question but you can consider it). Example of use on your queries:
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$insertQuery = $db->prepare('INSERT INTO monster VALUES ("", :name, :soort)');
$deleteQuery = $db->prepare('DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL');
//to execute query:
$deleteQuery->execute();
//or with params:
$insertQuery->execute(array(
':name' => $_POST['name'],
':soort' => $_POST['soort'],
));
Cool, huh? There is more... Now according to your problem it could be everything (as we don't have error log) but my guess is:
Try to use <?php instead of <?
$escape = "INSERT INTO monster VALUES ('',{$_POST["name"]},{$_POST["soort"]})";
EDIT:
As you provided error log - now I'm sure that problem is in $escape query. It's because you used $escape = " <- and then $_POST["name"] so there was a collision of " (if I can say so).
Try this:
Whenever you insert string type of values in the database using query it has to pass in the quote format. So you just need to change your insert query here.
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
write query like this.
-
Thanks

Cannot insert data into mysql table via php

I'm sure this question has been asked a thousand times but after an hour of truly trying many examples on the web, I have failed to insert new data into my table. I have tried many methods as I said, the one I'm about to post is most recent. If anyone knows why my code is failing it would save so much stress. I have only so far managed to insert data via phpmyadmin. The database is called "test" and the table is called "getting". Please note that "key" is auto incremented.
Thank you
$username='****';
$password='****';
$database='test';
$con= mysql_connect("localhost",$username,$password);
mysql_select_db("test",$con);
mysql_query("INSERT INTO getting (Key, Date, amount, tax, Extra)
VALUES ('', 'sept 26 2008', '35653', '46', '454')");
You should try
put keywords between backticks
format date as YYYY-MM-DD
don't use quotes for numbers
use NULL for auto-increment keys (you could also remove it from INSERT)
perform error checking
Try this query
$res = mysql_query(
"INSERT INTO getting (`Key`, `Date`, amount, tax, Extra)
VALUES (NULL, '2008-09-26', 35653, 46, 454)");
if (!$res) {
die('Invalid query: ' . mysql_error());
} else {
// Do here what you need
}
mysql_query("INSERT INTO getting (Key, Date, amount, tax, Extra)
VALUES ('', 'sept 26 2008', '35653', '46', '454')") or die(mysql_error());
What does it say after execution? If there is an error in request - you will see it.
my guess would have been "4. use NULL for auto-increment keys" by marco too
I belive if the 'key' filed is autoincremented you may not even bother mentioning it in your insert statement.
Something like this
INSERT INTO getting (Date, amount, tax, Extra)
VALUES ('sept 26 2008', '35653', '46', '454')

Categories