PHP code from registration procedure:
$query="INSERT INTO `users`(`email`, `password`, `role`, `time_registration`)
VALUES ('".mysqli_real_escape_string($con, trim($_SESSION['reg']['email']))."',
'".hash('SHA512',trim($_POST['password']))."',
'".mysqli_real_escape_string($con, trim($_SESSION['rola']))."',
NOW())";
if(!mysqli_query($con, $query)){
error(".....");
}else{
Here is all good. First query is executed and data is stored to table "users". But here comes problem. Next php code generate new mysql query, which is never executed. But when I copy it to PHPmyAdmin, there it works...
$last_id=$con->insert_id;
$query='';
foreach($_SESSION['reg'] as $key=>$value){
if($value!=''){
$query.=" INSERT INTO user_detail (id_user,id_item,value) VALUES ('".$last_id."', (SELECT id_item FROM profil_items WHERE name='".$key."'), '".mysqli_real_escape_string($con, $value)."');";
}
}
if(!mysqli_query($con, $query)){
echo $query;
}else{
header('Location: ...somewhere....');
}
}
Mysqli error message: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO user_detail (id_user,id_item,value) VALUES ('14', (SELECT id_po' at line 1".
I dont understand. If there is an error in syntax, how can by executed without errors in PHPmyAdmin?
There is never any reason to use mysqli_multi_query(). Starting a habit of using multi-query opens yourself up to new types of SQL injection vulnerabilities.
You should either execute each INSERT individually, with mysqli_query() inside the foreach loop.
Or else append multiple rows into one multi-row INSERT statement and execute it after the loop.
In this case, no (though you should use bound parameters instead of mysqli_real_escape_string()), but I think once you start using mysqli_multi_query() you may use it elsewhere in an unsafe manner. Better to never use it.
You can execute a single INSERT by using multi-row syntax. But I wouldn't worry about the overhead of executing multiple statements, until you are doing it in such high volume that you can measure a significant performance problem. Don't worry about micro-optimizations.
Related
I am trying to create a trigger into mySQL using PHP
mysqli_select_db($host, "game");
$sql = "CREATE TRIGGER test_seven BEFORE INSERT ON test FOR EACH ROW INSERT INTO test (name) VALUES ('test')";
$query = $host->prepare($sql);
$query->execute();
And it is not working even though I tried running it on phpMyAdmin and it worked.
EDIT: "This command is not supported in the prepared statement protocol yet"
Is there a way of skipping the prepare statement then ?
Apparently the real problem was the fact that I was not supposed to use the PDO::prepare statement, if anyone else is having this issue use PDO::exec.
I am currently learning PHP and am using the query below to insert values into my MySQL table.
I would like to check whether or not the values were inserted correctly. I have tried writing an IF statement and have searched through numerous examples, none of which seem to be working.
I would appreciate any help in steering me in the right direction.
$dd_tracking_insert = $dd_tracking_conn->query("INSERT INTO $dd_tracking_table_name (invoice_id, user_id, gc_bill_id, gc_bill_amount, gc_bill_fees, gc_bill_status, gc_bill_created) VALUES ('$invoice_id', '$user_id', '$gc_transaction_id', '$invoice_amount', '$gc_fees', '$gc_status', now())");
IF inserted correctly - echo "inserted".
If Error: was not inserted -echo "error: values where not inserted correctly."
Link to full code here
To check if your INSERT was successful, you can use mysqli_affected_rows().
http://php.net/manual/en/mysqli.affected-rows.php
Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.
Object oriented style
int $mysqli->affected_rows;
Procedural style
int mysqli_affected_rows ( mysqli $link )
And check for errors against your query and for PHP.
References:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
Your present code is open to SQL injection if user interaction is involved.
Use mysqli with prepared statements, or PDO with prepared statements.
if (!$dd_tracking_conn->query("INSERT...")){
//echo "error: values where not inserted correctly.";
printf("Error: %s\n", $dd_tracking_conn->error);
}else {
echo "inserted";
}
$nam=$_POST['name'];
$fname=$_POST['family'];
$dat=$_POST['date'];
$bal=$_POST['balance'];
$curr=$_POST['currency'];
$con=mysql_connect('localhost', 'xxxx', 'xxxx', 'xxxx');
$db=mysql_select_db('users',$con);
$ins=mysql_query("INSERT INTO users (Name, FamilyName, Date, Balance, Currency) VALUES ('$nam', '$fname', '$dat', '$bal', '$curr'))",$con);
if (!mysql_query($ins,$con))
{
die('Error: ' . mysql_error($con));
}
So guys, I got this code and I am trying to do something like a registration form. I have tripple checked the names of the variables and the query itself is working when executed in SQL database. The thing is when I include it in my php script it returns that the Query was empty. I've looked around but all errors on the Web are around not assigning to a variable or having several insert statements and so on. So my question is why am i getting this when I am actually inputting data from a web form? Error: Query was empty
P.S.
Ok so what I mde of this: I removed the check that you said was for a second time that is the if (!mysql_query($ins,$con)) { die('Error: ' . mysql_error($con)); } part now i get execution but it does not really add the entry to the database and i cannot call it. That is the new name.
You're basically trying to use mysql_query() twice:
$ins=mysql_query("INSERT INTO users (Name, FamilyName, Date, Balance,
Currency) VALUES ('$nam', '$fname', '$dat', '$bal', '$curr'))",$con);
if (!mysql_query($ins,$con))
{
$ins will contain a valid MySQL resource if the query was executed correctly, but you're attempting to use it again in the if condition.
Just remove the mysql_query() part from the condition, like so:
if(!$ins) {
# code ...
}
That should fix this particular issue. But note that your code is vulernable to SQL injection. Also, mysql_* functions are deprecated and are soon to be removed. I recommend you switch to MySQLi or PDO and start using parameterized queries to be safe.
this is incorrect
if (!mysql_query($ins,$con))
why are you performing a query of a query ??
just use if (!$ins||!$con)) if you are trying to check if the query and connection has been successful
I'm having an issue with a MySQL query when run in php. It works fine when I run it in PHPMyAdmin or SequelPro, but when copied into the PHP file it is meant to run in, it stops working.
The query is designed to take data from multiple tables that are linked with Primary Keys, and then put that data into corresponding identical tables. I know it's an odd thing to do, but it needs to do it.
Query (as used in a PHP file) is as follows:
for($x = 0; $x < count($REQIDARRAY); $x++){
$sql="BEGIN;
INSERT INTO `Request`
SELECT NULL AS `RequestID`, `ModCode`, `RoomID`, `Students`, `Priority`, `Day`, `StartTime`, `Length`, `Semester`, `DateAdded`, `SpecialRequests`
FROM RequestTEMP
WHERE RequestTEMP.RequestID=\"".$REQIDARRAY[$x]."\";
INSERT INTO `Week`
SELECT `WeekNumber` , LAST_INSERT_ID() AS `RequestID`
FROM `WeekTEMP`
WHERE WeekTEMP.RequestID=\"".$REQIDARRAY[$x]."\"';
INSERT INTO `RequestFacilities`
SELECT LAST_INSERT_ID() AS `RequestID` , `FacilityID`
FROM `RequestFacilitiesTEMP`
WHERE RequestFacilitiesTEMP.RequestID=\"".$REQIDARRAY[$x]."\"';
DELETE FROM `RequestTEMP` WHERE RequestID=\"".$REQIDARRAY[$x]."\";
DELETE FROM `RequestFacilitiesTEMP` WHERE RequestID=\"".$REQIDARRAY[$x]."\";
DELETE FROM `WeekTEMP` WHERE RequestID=\"".$REQIDARRAY[$x]."\";
COMMIT;";
$DB->Query('TransferMe' , $sql);
}
I have confirmed that $REQIDARRAY[$x] is returning correct values.
When running it in SequelPro, all that changes is that I would change
RequestID=\"".$REQIDARRAY[$x]."\"
to
'RequestID='123'
The error message in PHP is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO Request SELECT NULL AS RequestID, ModCode, RoomID, `Student' at line 2.
MySQL Version is 5.1.60.
I have no idea what is causing the problem, I've also tried hard coding values for RequestID into the PHP file and it still returns the same error.
Any help much appreciated!
The library you using is using mysql_query() function, which cannot run multiple queries at once (as a protection against SQL injection).
You need to run each of your queries with separate call to $DB->Query(). Don't worry, it will still be treated as a single transaction.
Example:
$sql="BEGIN";
$DB->Query('TransferMe' , $sql);
$sql = "INSERT INTO `Request`
SELECT NULL AS `RequestID`, `ModCode`, `RoomID`, `Students`, `Priority`, `Day`, `StartTime`, `Length`, `Semester`, `DateAdded`, `SpecialRequests`
FROM RequestTEMP
WHERE RequestTEMP.RequestID=\"".$REQIDARRAY[$x]."\";";
$DB->Query('TransferMe' , $sql);
...
Also: you might want to look at some more modern ways of accessing MySQL from PHP like ext/MySQLI (recommended by developers of MySQL) or PDO (favourited by majority of PHP coders)
I'm having problems with an INSERT statement, and the error only says:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
It's not helpful at all.
The version I have tried so far and failed is:
mysql_query("INSET INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
[needless to say that the two variables when printed show the right values]
I've also tried versions with nothing around the table name, with ` or ', a million combinations really and nothing works. Not even with constants or into different tables. It just won't insert anything ever. I've checked the privileges (I'm logging into it with root), and it's all on.
I've tried similar stuff on two different machines with the same server (XAMPP 1.7.7) and it works. I'm completely baffled! What can it be?
Thank you for your time!
First and foremost, just type INSERT correctly.
Using _GET like that really opens you up to SQL INJECTIONS...
Do take a look into MySQL prepared statements.
It is also considered good practice to name the columns that you're inserting data into. That allows you to, latter on, insert extra-columns and keep application logic.
INSERT INTO cos(rowName1, rowName2) VALUES(?, ?)
Where ? would be prepared statements.
Correct:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')");
Have you tried passing the $link to mysql_query ?
Like:
mysql_query("INSERT INTO `cos` VALUES ('".$_GET['prod']."','".$_GET['page']."')", $link);
EDIT:
And of course you must take some security measures before inserting anything into the database, maybe mysql_real_escape_string() or even prepared statements.
You are doing it wrong. Why aren't you escaping the values?
Php.net documentation is providing some good and safe working examples:
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
So adapted to your code:
$query = sprintf("INSERT INTO `cos` VALUES (%s, %s);",
mysql_real_escape_string($_GET['prod']),
mysql_real_escape_string($_GET['page']));
$result = mysql_query($query);
Please, always escape your values. And use INSERT, not INSET :)
first this is you are using INSET make it correct with INSERT like
$pro = mysql_real_escape_string($_GET['prod']);
$page = mysql_real_escape_string($_GET['page']);
mysql_query("INSERT INTO `cos` (column1, column2)
VALUES ('$pro', '$page')" );
you forget to set the column names...
Try this:
$prod = $_GET['prod'];
$page = $_GET['page'];
mysql_insert("INSERT INTO 'cos' VALUES('$prod','$page)");
This should very well do it :)