PHP MYSQL Data fetching issue - php

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

Related

How to insert into postgre database without concatenate strings?

My code is like this:
$sql = "INSERT INTO oraculo VALUES(".$name.$pass.")";
pg_query($dbconn, $sql);
In java i use PreparedStament to insert values without concatenate strings (to avoid sql injection if im right). Is possible to do something like this in PHP? Im want to do something like this:
$sql = "INSERT INTO oraculo VALUES(?, ?)";
//set the value of first '?'
setValue(1, "somename");
//set the value of second '?'
setValue(2, "somepass");
pg_query($dbconn, $sql);
You can use pg_prepare to execute prepared statements to postgres in PHP.
So your code would look like:
pg_prepare($dbconn, "login", 'SELECT * FROM shops WHERE name = $1');
$rs = pg_execute($dbconn, "login", array("somename", "somepass"));

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

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

What is the proper syntax for inserting variables into a SELECT statement?

I believe I have a simple syntax problem in my SQL statement. If I run this code, I get an error in the database query.
$user = $_GET['linevar'];
echo $user; // testing - url variable echos correctly
$sql = "SELECT * FROM `userAccounts` WHERE `name` = $user";
$result = mysql_query($sql) or die("Error in db query");
If I replace $user in the $sql string with 'actualName' or a known record in my table, the code works fine. Am I using the $ variable incorrectly in the SQL string?
You need to surround the value that you're getting from $user with quotes, since it's probably not a number:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
Just as a note, you should also read up on SQL injection, since this code is susceptible to it. A fix would be to pass it through mysql_real_escape_string():
$user = mysql_real_escape_string( $_GET['linevar']);
You can also replace your or die(); logic with something a bit more informative to get an error message when something bad happens, like:
or die("Error in db query" . mysql_error());
You need escape the get input, then quote it.
// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
This should work:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";

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.

Categories