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";
}
Related
I have an issue with my prepared statement that is being sent through PHP to my database. Can someone tell me why the below statement does not return the result? I'll just describe what I want it to do, what its doing and the code.
I have data being sent through a form that is ready to be inserted into one of my tables but I need to get a value from another table to insert.
I used to the following SELECT statement to get the tripNo based off the data entered. This query works on MySQL Workbench and returns the correct result, but it doesn't work on my php form. The result is null when I echo $tripNo.
Code:
$destination=$_POST['destination'];
$dateOfSail=$_POST['dateOfSail'];
$db = createConnection();
$sql="select tripNo from TripDB where dateOfSail=? AND destination=?;";
$stmt=$db->prepare($sql);
$stmt->bind_param("ss",$dateOfSail,$destination);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($tripNo);
echo "tripNo: $tripNo"; //returns null value
There are no errors being reported so I am not sure where to investigate next as I have looked at the prepared statements examples.
Also, I have a side question. Is the method bad practice on getting a value in order to insert to a table?
after the bind_result you have to perform fetch:
while ($stmt->fetch()) {
echo "tripNo: $tripNo<br />";
}
The PHP code I have inserts the HTML form data from the previous page into the database and in the same SQL statement return the PostID back from the inserted data. The PostID column is AUTO_INCREMENTING. I have been researching this problem for a week or two now and have found no significant solutions.
<?php
include("dbconnect.php");
mysql_select_db("astral_database", $con);
session_start();
$username = $_SESSION['username'];
$forumtext = $_POST["forumtext"];
$forumsubject = $_POST["forumsubject"];
$postquery = 'INSERT INTO Forums (Creator, Subject, Content) VALUES ("$username", "$forumsubject", "$forumtext"); SELECT LAST_INSERT_ID()';
$result = mysql_query($postquery, $con);
if (!$con) {
echo "<b>If you are seeing this, please send the information below to astraldevgroup#gmail.com</b><br>Error (331: dbconnect experienced fatal errors while attempting to connect)";
die();
}
if ($username == null) {
echo "<b>If you are seeing this, please send the information below to astraldevgroup#gmail.com</b><br>Error (332: Username was not specified while attempting to send request)";
die();
}
if ($result != null) {
echo "last id: " . $result;
$fhandle = fopen("recentposts.txt", "r+");
$contents = file_get_contents("recentposts.txt");
fwrite($fhandle, json_encode(array("postid" => $result, "creator" => $username, "subject" => $forumsubject, "activity" => time())) . "\n" . $contents);
fclose($fhandle);
mysql_close($con);
header("location: http://astraldevgroup.com/forums");
die();
} else {
die("<b>If you are seeing this, please send the information below to astraldevgroup#gmail.com</b><br>Error (330: Unhandled exception occured while posting forum to website.)<br>");
echo mysql_error();
}
mysql_close($con);
?>
First off, the mysql_query doesn't return anything from the SELECT statement. I haven't found anything that will properly run both the SELECT statement and the INSERT statement in the same query. If I try running them in two different statements, it still doesn't return anything. I tried running the following statement in the SQL console and it ran perfectly fine without errors.
INSERT INTO Forums (Creator, Subject, Content) VALUES ("Admin", "Test forum 15", "This is a forum that should give me the post id."); SELECT LAST_INSERT_ID();
The mysql_query function does not run multiple statements
Reference: http://php.net/manual/en/function.mysql-query.php
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server ...
That's one reason your call to mysql_query isn't returning a resultset.
The most obvious workaround is to not try to run the SELECT in the same query. You could use a call to the mysql_insert_id instead.
Reference: PHP: mysql_insert_id http://php.net/manual/en/function.mysql-insert-id.php
Answers to some of questions you didn't ask:
Yes, your example code is vulnerable to SQL Injection.
Yes, the mysql_ interface has been deprecated for a long time.
Yes, you should being using either PDO or mysqli interfaces instead of the deprecated mysql_ functions.
FOLLOWUP
Re-visiting my answer, looking again at the question, and the example code.
I previously indicated that the code was vulnerable to SQL Injection, because potentially unsafe values are included in the SQL text. And that's what it looked like on a quick review.
But looking at it again, that isn't strictly true, because variable substitution isn't really happening, because the string literal is enclosed in single quotes. Consider what the output from:
$foo = "bar";
echo '$foo';
echo '"$foo"';
Then consider what is assigned to $postquery by this line of code:
$postquery = 'INSERT ... VALUES ("$username", "$forumsubject", "$forumtext")';
Fixing that so that $username is considered to be a reference to a variable, rather than literal characters (to get the value assigned to $username variable incorporated into the SQL text) that would introduce the SQL Injection vulnerability.
Prepared statements with bind placeholders are really not that hard.
$result will never be null. It's either a result handle, or a boolean false. Since you're testing for the wrong value, you'll never see the false that mysql_query() returned to tell you that the query failed.
As others have pointed out, you can NOT issue multiple queries in a single query() call - it's a cheap basic defense against one form of SQL injection attacks in the PHP mysql driver. However, the rest of your code IS vulnerable other forms of injection attacks, so... better start reading: http://bobby-tables.com
Plus, on the logic side, why are you testing for a null username AFTER you try to insert that very same username into the DB? You should be testing/validating those values BEFORE you run the query.
I need to insert data from a table named wishlist into another table (wishlisturi_salvate) and altough the insert looks ok, something doesn't work right and no inseration is being made.Thanks for the help, I really appreciate it.
<?php
session_start();
include ('conex.php');
$sel2="select id_wishlist from wishlisturi_salvate";
$que2=mysql_query($sel2);
while($rez2=mysql_fetch_array($que2))
{
$a=$rez2['id_wishlist'];
}
$id_wishlist=$a;
echo $id_wishlist;
$sel="SELECT * from wishlist";
$que=mysql_query($sel);
while ($rez=mysql_fetch_array($que))
{
$insert="INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma')
VALUES('".$_SESSION['id']."','".$id_wishlist."','".$rez['id_produs']."','".$rez['nume_produs']."','".$rez['pret_produs']."','".$rez['cantitate_produs']."','".$rez['suma']."')";
if(!mysql_query($insert)) echo "fml";
echo "<br>".$insert;
}
if(mysql_query($insert))
{
header("location:user.php");
}
else echo "Nu s-a facut inserarea";
?>
No insertion is being made most likely because of the errors inside the query:
Right of the bat, there is already an error:
INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma')
The proper quoting of table/column names must be backtickts, not single quotes
INSERT INTO `wishlisturi_salvate` (`id_user`, `id_wishlist`, `id_produs`, `nume_produs`, `pret_produs`, `cantitate_produs`, `suma`)
Or just omit them, its okay in this case.
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Sidenote:
If you haven't already, always turn on error reporting:
error_reporting(E_ALL);
ini_set('display_errors', '1');
First of all I'll rcomend you to use PDO or mysqli instead of mysql to avoid SQL injection.
Anyway, if you want to insert elements from one table to another one I recommend you to use an insert statment with a subselect. That way it'll be faster and you will waste less memory.
Not an answer, more of an observation ; It will be far more efficient to loop through your results to build up a single SQL insert multiple statement that you send to the db once.
$insert = "INSERT INTO 'wishlisturi_salvate'('id_user', 'id_wishlist', 'id_produs', 'nume_produs', 'pret_produs', 'cantitate_produs', 'suma') VALUES ";
foreach( of your results ){
$insert .= "(x,y,z,a,b,c,d),";
}
// now trim off last comma, then send to db.
// or create an array then join it to the $insert
Same info can be read here : http://www.electrictoolbox.com/mysql-insert-multiple-records/
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.
$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