mysql_fetch_row() not a valid result resource - php

I am confused, I don't know what's wrong. I'm about to transfer all data from my first table to the other. Here is my code:
$getdata = mysql_query("SELECT Quantity, Description, Total FROM ordercart");
while($row = mysql_fetch_row($getdata))
{
foreach($row as $cell){
$query1 = mysql_query("INSERT INTO ordermem (Quantity, Description, Total) VALUES
($cell)",$connect);
}
mysql_free_result($getdata);
}
I get the error: Warning: mysql_fetch_row(): 5 is not a valid MySQL result resource.

You only pass one value in the INSERT, which expects three values to be passed to the fields Quantity, Description, Total:
INSERT INTO ordermem (Quantity, Description, Total) VALUES
($cell);
Change it to:
INSERT INTO ordermem (Quantity, Description, Total) VALUES
($cell, $descriptionParam, $totalParam);
You may also try to use INSERT INTO SELECT directly instead of two distinct statements like so:
INSERT INTO ordermem (Quantity, Description, Total)
SELECT Quantity, Description, Total FROM ordercart;

You are trying to insert 1 value into 3 fields. You need to have 1 value for each field. For example:
$quantity="$_GET['qty']";
$description="$_GET['desc']";
$total="$_GET['total']";
$query = mysql_query("INSERT INTO ordermem (Quantity, Description, Total)
VALUES ('$quantity','$description','$total'))

Use debugging to find out the source of your problem.
mysql_query() returns a boolean value that tells you whether the operation succeeded or not. If it did not succeed, the mysql_error() function give you mySQL's error message.
Example:
$query1 = mysql_query("INSERT INTO ordermem (Quantity, Description, Total) VALUES ($cell)",$connect);
if (!$query1)
trigger_error("mySQL Error: mySQL returned ".mysql_error(), E_USER_ERROR);
This will give you a message something like "Number of values does not match the number of columns", which gives you a hint about what's wrong.

Try this :
$query = "INSERT INTO ordermem (Quantity, Description, Total) SELECT Quantity, Description, Total FROM ordercart";
mysql_query($query);

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

MYSQL insert values with select

I'm trying to insert values like this:
$sql = "INSERT INTO daily_food (number, weight, title, price) VALUES ('1', SELECT weight, title, price FROM food where title = '$add_food' LIMIT 1)";
mysqli_query($conn, $sql);
I have database with food which i'm selecting from. I would like to insert that number aswell but code is doing nothing. I'm new in sql so i can't figure out how the code should look.
Just use insert . . . select, values is not necessary:
INSERT INTO daily_food (number, weight, title, price)
SELECT 1, weight, title, price
FROM food
WHERE title = '$add_food'
LIMIT 1;
Im assuming that number is, indeed, a number, so quotes are not needed.
In addition, you should be passing in $add_food as a parameter, something like this:
INSERT INTO daily_food (number, weight, title, price)
SELECT 1, weight, title, price
FROM food
WHERE title = ?
LIMIT 1;

Store query result as php variable

Before you spam as duplicate I have read through around 20-30 posts on this site about how to do this as well as others and I can't get mine to work so thats why i am asking the question.
I have the following code:
$lookupID = "SELECT ID FROM dungeon WHERE Name = '$loc'";
$result = mysqli_query($connection, $lookupID);
$row = mysqli_fetch_row($result);
$locID = $row['ID'];
$query = "INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty) VALUES ('0', '$boss', '$type', '$loc', '$locID', '$diff')";
The purpose for the lookupID is to based upon the $loc value lookup in the other table what the locID value associated with it is and set $locID to that number. Currently when I run the query I get the following:
Error: INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty) VALUES ('0', 'Godzilla', 'Lizard', 'Black Rock Hold', '', '4')
With the locID variable giving no value and so causing the error. Im sure its something simple and stupid I am doing but I am new to php and mysql so I hope you forgive me.
The mysqli_fetch_row function returns the array with enumerated keys, so you should use
$locID = $row[0];
If you want, you can use mysqli_fetch_assoc to get the row with associative keys instead.

How to insert the product of two variables into a table if one of them is stored in another table?

Good evening everybody.
Here is my issue:
I have a list of variables which is defined by an 'extract' command. They are numeric values that represent the number of wooden boards produced in a sawmill.
Another list of variables is stored in an SQL table. They represent the volume coefficients that come from the different sizes of lumber produced.
The idea is that a person could enter the number of boards of a certain size in an input field. The two numbers are then multiplied by each other to result in a general volume of lumber produced and are to be inserted into an SQL table.
The specification table containing the volumes also contains the variable names for the amount, if needed.
There needs to be some kind of automated loop that cycles all the variables carrying numeric values for the number of boards produced because new specifications can be added anytime that will create new variables for the amount.
I think I want to make work something like this:
$query = "SELECT * FROM Rspecs";
$result = mysql_query($query);
while( ($row = mysql_fetch_array($result)))
{
$conn->exec("INSERT INTO Eprocessing (date, amount, product, sort, notes, type, optype)
VALUES
('$date', '$amount*.$row['volume'].', '.$row['product'].', '0-3', '$notes', '$type', 'Processing')");
}
This obviously highly incorrect syntax represents what I want to do mostly. Please help me bringing this into a correct form.
thanks to everybody in advance.
$conn->exec("INSERT INTO Eprocessing
(date, amount, product, sort, notes, type, optype)
VALUES
('$date', '.$row['volume']. * $v22703', '$type', '0-3', '$notes', '$type', 'Processing')
('$date', '.$row['volume']. * $v291453', '$type', '0-3', '$notes', '$type', 'Processing')
('$date', '.$row['volume']. * $v291003', '$type', '0-3', '$notes', '$type', 'Processing')");
You don't need first query and loop, just this simple:
$conn->exec("INSERT INTO Eprocessing (date, amount, product, sort, notes, type, optype)
SELECT '$date',
($amount * rs.volume),
rs.product,
'0-3',
'$notes',
'$type',
'Processing'
FROM Rspecs rs;");
You have some syntax errors. When you are trying to cancatenate a variable which is an array index, you should wrap with {}
so your query should look like this,
$amt = $amount * $row['volume'] ;
$conn->exec("INSERT INTO Eprocessing (date, amount, product, sort, notes, type, optype) VALUES ('$date', ' $amt', '{$row['product']}' , '0-3', '$notes', '$type', 'Processing')");

Select Max inside a mysql Insert Query

Max(sequence) + 1 (based on my knowledge) should be returning the highest sequence with $_GET['business_id'] in the database + 1 - existing values in the database are 0, 1, and 3 - so max(sequence)+1 should be 4 - so something must be wrong with the line of code. Any ideas?
$insertQuery = "
INSERT INTO owner_business_media
(business_id, sequence, type, filename, title, secret)
VALUES (
'".$_GET[businessid]."',
'(SELECT MAX(sequence)+1 FROM owner_business_media WHERE business_id=".$_GET['businessid'].")',
'$type',
'$fullfile',
'$filename',
'1')
";
Remove single quotes that surround the inner SELECT and instead of the regular INSERT go with INSERT ... SELECT:
$insertQuery = "
INSERT INTO owner_business_media
(business_id, sequence, type, filename, title, secret)
SELECT
'".intval($_GET['businessid'])."',
(SELECT MAX(obm.sequence)+1 FROM owner_business_media obm WHERE obm.business_id=".intval($_GET['businessid']).") AS next,
'$type',
'$fullfile',
'$filename',
'1'
";
Also, never embed a GET variable directly without validating or sanitizing it's contents (see intval($_GET['businessid'])). Otherwise the code gets exposed to SQL injection.
Almost the same as the other answer, yet not completely the same:
$insertQuery = "
INSERT INTO owner_business_media
(business_id, sequence, type, filename, title, secret)
SELECT
'".intval($_GET['businessid'])."',
MAX(sequence)+1 AS next,
'$type',
'$fullfile',
'$filename',
'1'
FROM owner_business_media
WHERE business_id=".intval($_GET['businessid']);
Maybe it would be safer to use IFNULL with sequence (in case the table is empty), like this:
MAX(IFNULL(sequence, 0))+1 AS next

Categories