My insert statement (php to mysql) fails to use my variables - php

It must be the simplest error, but I dont see nor find it.
I fill a variable $aa_minerid with value 7.
I use this variable in a insert.
The insert always inserts a 0 (zero) in the database never a 7
The field i put it in is a smallint(6)
I tried
VALUES ('$aa_productid')
VALUES ($aa_productid)
VALUES ("$aa_productid")
VALUES ('{$aa_productid}')
VALUES ("{$aa_productid}")
and all with use of ` aswell
into script placed hereafter.
If I put there : VALUES ( 7 )
It does work perfect.
So what do I do wrong in this script?
BTW the echo at the end DOES show the right value of the variable $aa_productid
<?php
/* This php script should transfer data from the aa to the sql database */
// Info coming from aa
$aa_productid = 7 ;
include ("dogs.inc");
$cxn=mysqli_connect($host,$user,$passwd,$dbname);
$query = 'SELECT * FROM `Price` WHERE '
. ' `Time_Stamp`=(select max(`Time_Stamp`) from `Price` where `Product_ID` = \'1\')';
$result=mysqli_query($cxn,$query) or
die("Couldn't execute select query");
$row = mysqli_fetch_row($result);
$aa_price=$row[3] ;
$aa_value = $aa_price * $aa_amount;
// Info ready to go to database
$sqlinsert = 'INSERT INTO Mining (Product_ID)'
. ' VALUES ( $aa_productid )' ;
echo $aa_productid;

Single quotes don't do variable expansion in PHP. But I would recommend you use prepared statements, such as:
$stmt = $cxn->prepare('INSERT INTO Mining (Product_ID) VALUES ( ? )');
$stmt->bind_param('i', $aa_productid);
$stmt->execute();
See the documentation at prepare and bind_param.
This will protect you from SQL injection.

Try
'.$aa_productid.'
or
".$aa_productid."
Depending on the type of apostrophe used to beging the string, use the same one.
Also, if You are using ", then You should be able to Just do
$insert="INSERT INTO $tablename;";

It's been a while since I have done any PHP but..
I think you need to have smartquotes turned on
Try this instead:
$sqlinsert = 'INSERT INTO Mining (Product_ID)'
. ' VALUES ('. $aa_productid .' )' ;
concatenate the variable into the query.

When you are using variables within quotes, you must use the double-quote if you want PHP to parse variables within it. So, this would work:
$sqlinsert = 'INSERT INTO Mining (Product_ID) VALUES ('.$aa_productid.')';
Or this would:
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ($aa_productid)";

Try:
$query = "SELECT * FROM Price WHERE Time_Stamp=(select max(Time_Stamp) from Price where Product_ID = "1")";
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ( '$aa_productid' )" ;
Also, its always a good idea to escape the strings before entering them in the db.

Try this syntax instead:
$sqlinsert = "INSERT INTO Mining (Product_ID) VALUES ("' . $aa_productid . '")";
no need to concatenate the two parts of the insert. Also double quoting the variable seems to avoid problems.

Related

INSERT INTO TABLE .. php - variable in sql query

I have php script containing following SQL query (working oK):
$query = 'INSERT INTO persons'.
'(name,
surname
)'.'VALUES
( "'.$_REQUEST["name"].'",
"'.$_REQUEST["surname"].'"
)';
Where $_REQUEST["name"] and $_REQUEST["name"] are variables passed from html form.
usin php 4.5 and MariaDB 5.5
Problem rises when i try to substitute persons by variable - eg. $table:
$table = "persons";
$query = 'INSERT INTO '.$table.''.
'(name,
surname
)'.'VALUES
( "'.$_REQUEST["name"].'",
"'.$_REQUEST["surname"].'"
)';
I have been trying different variations with double qutes/single qutes/dots :). But still struggling with this..
Thx for possible answer.
Its a simply case of knowing how the single and double quote works in PHP
Try this
$table = 'persons';
$query = "INSERT INTO $table (name,surname)
VALUES ( '{$_REQUEST['name']}',
'{$_REQUEST['surname']}' )";
Now of course you should not be using the mysql_* extension anymore but if you have to you should at least try and sanitize the input values before you use them
So the code becomes
// do at least this to sanitize the inputs
$_REQUEST['name'] = mysql_real_escape_string($_REQUEST['name']);
$_REQUEST['surname'] = mysql_real_escape_string($_REQUEST['surname']);
$query = "INSERT INTO $table (name,surname)
VALUES ( '{$_REQUEST['name']}',
'{$_REQUEST['surname']}' )";
$table_name = 'persons';
$query = "insert into ".$table_name." (name,surname) values ('".$_REQUEST['name']."','".$_REQUEST['surname']."') ";

Php pdo insert query

I need to insert encrypted values in mysql table, but when I use traditional pdo method to insert its inserting the data in wrong format. ex: I insert aes_encrypt(value, key) in place of inserting encrypted value its inserting this as string.
Following is the code :
$update = "insert into `$table` $cols values ".$values;
$dbh = $this->pdo->prepare($update);
$dbh->execute($colVals);
$arr = array("col"=>"aes_encrypt ($val, $DBKey)");
I know i am doing it wrong, but not able to find correct way.
You are almost there, here is a simplified version:
<?php
$sql = "insert into `users` (`username`,`password`) values (?, aes_encrypt(?, ?))";
$stmt = $this->pdo->prepare($sql);
// Do not use associative array
// Just set values in the order of the question marks in $sql
// $fill_array[0] = $_POST['username'] gets assigned to first ? mark
// $fill_array[1] = $_POST['password'] gets assigned to second ? mark
// $fill_array[2] = $DBKey gets assigned to third ? mark
$fill_array = array($_POST['username'], $_POST['password'], $DBKey); // Three values for 3 question marks
// Put your array of values into the execute
// MySQL will do all the escaping for you
// Your SQL will be compiled by MySQL itself (not PHP) and render something like this:
// insert into `users` (`username`,`password`) values ('a_username', aes_encrypt('my_password', 'SupersecretDBKey45368857'))
// If any single quotes, backslashes, double-dashes, etc are encountered then they get handled automatically
$stmt->execute($fill_array); // Returns boolean TRUE/FALSE
// Errors?
echo $stmt->errorCode().'<br><br>'; // Five zeros are good like this 00000 but HY001 is a common error
// How many inserted?
echo $stmt->rowCount();
?>
you can try it like this.
$sql = "INSERT INTO $table (col) VALUES (:col1)";
$q = $conn->prepare($sql);
$q->execute(array(':cols' => AES_ENCRYPT($val, $DBKey)));

Insertion query in sql php function

i'am beginner in php and i have problem in insertion query
if(isset($id)){
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'.$id .') ";
$result = mysql_query($qry);
}
I'am connected to the database but the query didn't work.
Why it is not working? how can i correct it?
Don't create queries this way. It is very vulnerable to SQL injection.
Use a prepared statement instead. A prepared statement is precompiled, hence will not be subject to SQL injection.
$id = 99;
$tax = 8;
$stmt = $mysqli->prepare("insert into user_to_birds(user_id,tax_id)values(?,?)"));
$stmt->bind_param("ii", $user, $tax);
$stmt->execute();
.. work on it ..
$stmt->close();
ii stands for two integers. After that first part of the binding, telling which type of variables you use in which order, can you add the values of those variables to the statement. The values will be escaped automatically using this method.
if(isset($id)){
$qry = "insert into user_to_birds(user_id, tax_id)values('1','$id') ";
$result = mysql_query($qry);
}
Work like a charm.
I think your single quotes should be double quotes:
$qry = "insert into user_to_birds(user_id,tax_id )values( 1 ,".$id .") ";
You are confusing strings in PHP with strings in SQL (which is, admittedly, easy to do).
For how to insert into there's a nice article here
http://www.w3schools.com/php/php_mysql_insert.asp
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
//not sure if this will make a difference buy i would try a space between tax_id) and values(
also, im not sure if the way youve done it is wrong but i would have written like this
if(isset($id))
{
$qry = "insert into user_to_birds (user_id, tax_id)
values( '1' ,'".$id ."') ";
$result = mysql_query($qry);
}
look at string concatination aswell either have
" ' ' ".$variable." ' ' ";
in that fashion
As others have said, it looks like you're not using string concatenation correctly in your query. Try changing your query to something like:
$qry = "INSERT INTO user_to_birds (user_id,tax_id) VALUES ( 1 ,'$id') ";
Another possibility is that your $id variable isn't set. Try printing out the variale before doing the isset() check and that will tell you if you need to look at an earlier point in your code.
Finally, I'd recommend you look at mysqli functions rather than mysql.
http://php.net/manual/en/book.mysqli.php
You have some confusion in quotes: your string in " ", your sql value in ' ', but when you concatenate you need to close your string and write dot and variable, after this you need write dot, open string quotes again and write text if it needed. Your mistake - you didn't close string (") before concatenation and this leads to misinterpretation of the code. In this case your code will look like:
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'" .$id ."') ";
But you can not use concatenation,you can do it simply: PHP allows write your variable $id in string, without use concatenation:
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'$id') ";

PHP MYSQL Data fetching issue

I am facing some problem with fetching data from SQL.
When I use the below statement, it is working fine
$sql = 'SELECT `Name`, `Des`, `Url`, `about`, `date` FROM `data` where name = \'facebook\'';
$retval = mysql_query( $sql, $conn );
When I use the same using a parameter name, I am facing some problem, the code I used is
$name = $_GET['name'];
$sql = 'SELECT `Name`, `Des`, `Url`, `about`, `date` FROM `data` where name = \'$name'';
$retval = mysql_query( $sql, $conn );
I also tried by concatenating name like \'facebook\'
$name1 = "\'".$name . " \'"; but it is also not working .
use Double quotes so you won't need any escaping of single quotes.
$sql = "SELECT Name, Des, Url, about, date
FROM data
where name = '$name'";
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Use Mysqli instead of Mysql.
Solution for your query :
$name = $_GET['name'];
$sql = "SELECT Name, Des, Url, about, date FROM data where name = '".mysql_real_escape_string($name)."'";
$retval = mysql_query( $sql, $conn );

MySQL and PHP - insert NULL rather than empty string

I have a MySQL statement that inserts some variables into the database. I recently added 2 fields which are optional ($intLat, $intLng). Right now, if these values are not entered I pass along an empty string as a value. How do I pass an explicit NULL value to MySQL (if empty)?
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
'$intLat', '$intLng')";
mysql_query($query);
To pass a NULL to MySQL, you do just that.
INSERT INTO table (field,field2) VALUES (NULL,3)
So, in your code, check if $intLat, $intLng are empty, if they are, use NULL instead of '$intLat' or '$intLng'.
$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
$intLat, $intLng)";
This works just fine for me:
INSERT INTO table VALUES ('', NULLIF('$date',''))
(first '' increments id field)
If you don't pass values, you'll get nulls for defaults.
But you can just pass the word NULL without quotes.
All you have to do is: $variable =NULL; // and pass it in the insert query. This will store the value as NULL in mysql db
Normally, you add regular values to mySQL, from PHP like this:
function addValues($val1, $val2) {
db_open(); // just some code ot open the DB
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES ('$val1', '$val2')";
$result = mysql_query($query);
db_close(); // just some code to close the DB
}
When your values are empty/null ($val1=="" or $val1==NULL), and you want NULL to be added to SQL and not 0 or empty string, to the following:
function addValues($val1, $val2) {
db_open(); // just some code ot open the DB
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
(($val1=='')?"NULL":("'".$val1."'")) . ", ".
(($val2=='')?"NULL":("'".$val2."'")) .
")";
$result = mysql_query($query);
db_close(); // just some code to close the DB
}
Note that null must be added as "NULL" and not as "'NULL'" . The non-null values must be added as "'".$val1."'", etc.
Hope this helps, I just had to use this for some hardware data loggers, some of them collecting temperature and radiation, others only radiation. For those without the temperature sensor I needed NULL and not 0, for obvious reasons ( 0 is an accepted temperature value also).
For some reason, radhoo's solution wouldn't work for me. When I used the following expression:
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
(($val1=='')?"NULL":("'".$val1."'")) . ", ".
(($val2=='')?"NULL":("'".$val2."'")) .
")";
'null' (with quotes) was inserted instead of null without quotes, making it a string instead of an integer. So I finally tried:
$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
(($val1=='')? :("'".$val1."'")) . ", ".
(($val2=='')? :("'".$val2."'")) .
")";
The blank resulted in the correct null (unquoted) being inserted into the query.
your query can go as follows:
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$lng', '" . ($lat == '')?NULL:$lat . "', '" . ($long == '')?NULL:$long . "')";
mysql_query($query);
Check the variables before building the query, if they are empty, change them to the string NULL
you can do it for example with
UPDATE `table` SET `date`='', `newdate`=NULL WHERE id='$id'
2022 | PHP 7.3 | MySQL 5.7
Accepted answer by Rocket Hazmat gives me "NULL" as a string. So I change it to:
$intLat = !empty($intLat) ? "'$intLat'" : NULL;
$intLng = !empty($intLng) ? "'$intLng'" : NULL;

Categories