Insertion query in sql php function - php

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

Related

Inserting a variable with a comma in it to SQL database?

I've been trying to insert a variable that has a comma in it to a SQL database for 30 minutes or so. I've echoed the variable, and the comma is there, but when it inserts, there's no comma!
Example (some code like mine):
$variable1 = "test";
$variable2 = "$variable1,";
$sql1 = "INSERT INTO table (`column`) VALUES ('$variable2')";
$query1 = mysqli_query($con,$sql1); //I dont think I need to put a con variable up there for an example code
And when I do:
echo $variable2;
The result is test, with the comma, but the data in the column is just test WITH NO COMMA.
Help please.
Thanks.
Edit:
Your Common Sense fixed it, apparently I needed brackets around '$variable2' so it's like:
$sql1 = "INSERT INTO table (`column`) VALUES (('$variable2'))";
Thanks Your Common Sense and everyone else who tried!
Well, the answer is simple.
It's your own code does remove this comma, either before insert or after fetch.
If you care to write a reproduceable test case, you will see that noone is taking your comma.
Test case means code that involves the behavior in question and nothing else. Not a single line of code beside insert and fetch:
$variable1 = "test";
$variable2 = "$variable1,";
$sql1 = "INSERT INTO users (username) VALUES ('$variable2')";
mysqli_query($db,$sql1);
$sql2 = "SELECT username FROM users WHERE username ='$variable2'";
$res = mysqli_query($db,$sql2);
$row = mysqli_fetch_row($res);
var_dump($variable1, $variable2, $sql1, $sql2, $row[0]);
run it, see it all with comma in place, and then search your own code for the comma trimming code
or may be you have just test without comma in your table, ans select this one all the time, instead of one with comma.
or whatever silly error of the like
Try it like this:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("INSERT INTO table ('column') VALUES (?)");
$stmt->bind_param($variable2);
/* execute prepared statement */
$stmt->execute();
This is more safe and will not trigger such strangeties. (Is that a word?)
What happens here is, that the query is send to the sql database and this returns a statement. The statement has some holes, these are the ?, in it.
When using bind_param you fill the holes and then you can execute.
This has a couple of advantages:
It is safe
You can reuse your statement
It is easier than string interpolation stuff
Try "INSERT INTO table ('column') VALUES ('" . $variable2 . "');"

Parameterised IN Clause in prepared statement using MySql,PHP and ADODB

I am writing some SQL and using AdoDb to connect to my database and run the queries and so on. I am using parametrized queries and have run into a snag.
Is their a way to pass an array of values to an in_clause in AdoDb/MySql for parametrization.
My problem is that if I pass a prepared string as the parameter i.e. 'test','test2','test3' it does not work as the library or database auto escapes it and adds external quotes at the start and end so all the internal quotes are then auto escaped thus the query returns nothing as it looks for '\'test\',\'test2\',\'test3\'' as opposed to what I fed it.
UPDATED WITH ANOTHER POSSIBLE METHOD TO ACCOMPLISH THIS
<?php
$in_clause = implode(",", $first_names);
$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
FIND_IN_SET(mytable_fname," . $DB->Param('first_names') . ")"
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt,array($in_clause));
?>
I would do it this way (as I was googling for a while and google came up with nothing useful):
$count = count($first_names);
$in_params = trim(str_repeat('?, ', $count), ', ');
$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
mytable_fname IN ({$in_params});";
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt, $first_names);
This should do it...
First a few tips:
Please read carefully the AdoDB documentation on prepared statements.
Never include ; in SQL query strings.
You can try something like this:
$question_marks = substr(str_repeat('?,', count($first_names)), 0, -1);
$query = "SELECT mytable_id_pk FROM mytable WHERE mytable_fname IN (" . $question_marks . ")";
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt,$first_names);
WARNING: I haven't tested this (not having a mySQL installation here).

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

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.

Insert query problem with php mysql

This is simple one i am using the following insert query
mysql_query(insert into table1 set saltval = 'Y'Z' where uid ='1');
but i does not work becaues the value for the field saltval is Y'Z . my question is how to considered this value is as a string .
You need to escape any single quotes with a backslash.
mysql_query("insert into table1 set saltval = 'Y\'Z' where uid ='1'");
However your SQL is invalid as well... Did you mean to do an update? Insert statements don't have a where.
As mentioned in other answers, if the input is from a user then you should use mysql_real_escape_string()
http://www.php.net/manual/en/function.mysql-real-escape-string.php
$string = mysql_real_escape_string("Y'Z");
mysql_query("insert into table1 set saltval = '{$string}' where uid ='1'");
Always use mysql_real_escape_string() function for this if values come from user input
$query="insert into table1 set saltval = '".mysql_real_escape_string($InputVal)."' where uid ='1'";
See http://php.net/manual/en/function.mysql-real-escape-string.php
You have to add a backslash to certain characters to make your string fit into SQL syntax rules.
Assuming you're creating your query dynamically, PHP has special escaping function for this and you should use it for the every quoted string in the query, no exceptions.
So, write your code like this:
$salt = "Y'Z";
$id = 1;
$salt = mysql_real_escape_string($salt);
$id = mysql_real_escape_string($id);
$sql = "update table1 set saltval = '$salt' where uid ='$id'";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
to make it safe and fault-tolerant

mysql escaping single and double quotes

I have a script that i am writing to move certain fields to a new db like
$results = mysql_query ( "SELECT body, title FROM $source_db.Post" );
while ($row = mysql_fetch_array($results)) {
if(mysql_num_rows($users_result) > 0){
$insert = "INSERT INTO wp_posts (`body`,`title`) VALUES ('{$row['body']}', '{$row['row']}')";
mysql_query($insert);
}
}
but as you can see the query will break everytime due to the single and double quotes, is there a solution to this problem like herdok or something
INSERT INTO wp_posts (`body`,`title`)
VALUES
('Here are the final returns from today's ...<br /><br />he stayed home...<br />
<div class="entry-content">
<div class="entry-body">', 'something')
mysql_real_escape_string is made for just this.
PHP: mysql_real_escape_string
$insert = "INSERT INTO wp_posts ('body','title') VALUES ('".mysql_real_escape_string($row['body'])."', '".mysql_real_escape_string($row['row'])."')";
The other option is to use mysqli and prepared statements
$stmt = $this->db->prepare("insert into table (id,name,longstring) values (?,?,?));
$stmt->bind_param('iss',$row["id"],$row["name"],$row["body"]);
$stmt->execute();
mysqli will bind the assigned parameters to the ? in the prepared statement as an integer (i) or a string (s).
The sanest approach is to use bound parameters. Bobby Tables has examples.

Categories