I'm trying to execute this sql query using PHP
$sql="SELECT convert (varchar(500),Xml.query('for $i in /data/var1/text() return concat($i, "||")')) as var1 FROM #table1";
echo $sql;
$result = odbc_exec($connection, $sql);
i have a problem with $i, the variable is used in the loop in the sql query .
I tried to put it between singles quotes and doubles quotes, i also tried this : \'$i\' but it's not working.
If you $i is php variable, than you have to inject it like in code below:
$sql="SELECT convert (varchar(500),Xml.query('for ".$i." in /data/var1/text() return concat(".$i.", \"||\")')) as var1 FROM #table1";
I also escaped double quotes that you used in concat() function, they surely wouldn't work as you wrote it, but I'm not 100% sure if that way of escaping them gonna work - personally I'm avoiding similar situations.
Related
I'm creating a json array from MySql data using concat like this:
$id = '5705';
$sql = 'select concat("{""type:""colName"",""id"":""$id""}") as myJson from table where etc.;
$stmt = $conn->prepare($sql);
What's happening is, instead of getting data from colName from the table and the value of $id, I'm getting the result as it is in $sql. How do I break out of it and get colName and $id's value?
Current Result
{""type:""colName"",""id"":""$id""}
Desired Result
{""type:""novice"",""id"":""5705""}
//Here novice is data from colName, and 5705 is the value of $id
Please DON'T DO THAT. Trying to format data into JSON in your SQL will be fragile as encoding things into JSON is subtly more tricky that you would expect and you will inevitably get it wrong.
You should use the json_encode function in PHP. It will work reliably whereas your code will almost certainly break.
$dataArray = array();
while($statement->fetch()){
$data = array();
$data['type'] = $typeColumn;
$data['id'] = $id;
$dataArray[] = $data;
}
json_encode($dataArray, JSON_HEX_QUOT);
Also, formatting data to send to a client really shouldn't be part of an SQL query.
You need a better concatenation either in query and php
'select concat("{""type:"",colName,"",""id"":""'.$id.'""}")
Despite it is not really needed you could surround column name with backticks `
Your variables inside your string are not substituted with their values, as you got single quotes. Double quoted strings will expand variables with their values
Thus, you could invert your quotes, like this, in order to get the actual values of your variables:
$sql = "select concat('...')"
I have multiple values passed through a POST form (from multiple check boxes of previous page) and I stored them into an array $vals. Now I want to write a query string (in a while loop) that generates a slightly different query depending on how far in the loop it has been.
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
But it doesn't seem to work this way? I thought that by having double quotes for query, the
echo $vals[$i]
would generate the actual value of the current index in $vals[$i] and not the literal string? Is this what's happening? Can I not have php inside a query string that the mysql servers would accept?
lets just say i have a fooID in my server table that is '12345'. Even if I set $vals='12345' and write:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
it still doesn't work. I guess my general question would be: is it possible to write/get values of variables in a query string, and if not, is there another way around my situation? Any help is appreciated. Thanks!
You should not be placing the un-sanitized $_POSTed values into a SQL query. Look into using paramaterized arguments and mysqli.
You can output variables using the syntax:
$myVar = 'toast';
$combined = "I like $myVar";
However, this will not work as you would like for an array.
For an array, you'll want to look into using something like php's implode() to convert your array into a string first.
first of all never do queries in loop.
Second of all never use straight $_POST or $_GET or whatever client is passing in queries because you can be harmed by sql injections.wiki and also clearing data for mysql in php
ok so how it should be done (i am saying only about first one. second one i dont know how to make it without oop ).
<?php
$vals=($_POST['selectedIDs']);
$vals = implode(',',$vals);
$query = "SELECT * FROM List foo WHERE foo.fooID IN ($vals)";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
echo "YES IT WORKS!";
var_dump($row); //you will see all the data in one row
}
}?>
You have an extra echo in your SQL string:
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
It should be:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals[$i]";
Generally, it's a BAD idea to construct SQL strings from user input. Use prepared statements instead. Check here for more info on prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
Thanks you guys for the advice but it turned out, my code didn't execute correctly because of a syntax error (and the extra echo statement). my original code was missing quotation marks around $vals[$i]. This is a mysql syntax mistake because it didn't accept foo.fooID=12345 but did for foo.fooID='12345'. Here is the final code that solved it
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = '$vals[$i]'";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
I'm having some trouble with what I believe should be some fairly simple PHP. It's run inside of WordPress, but the question shouldn't be WordPress specific. The $wpdb->get_results() is just a way to query the WordPress database without having to use a connection string. I also use a couple of $_GET commands.
Here's what I have so far:
$Data = $wpdb->get_results("SELECT *
FROM database.table
WHERE sem.MonthNum >= " .$_GET["minMonth"]. "
AND sem.MonthNum <= " .$_GET["maxMonth"]. "
AND sem.Year >= " .$_GET["minYear"]. "
AND sem.Year <= " .$_GET["maxYear"]. ");
This works, so long as the $_GET is populated. I'd like to add a kind of default value such that if $_GET is empty, a number is set, and if it's not empty, it grabs that number. Something along the lines of...
$Data = $wpdb->get_results("SELECT *
FROM database.table
WHERE sem.MonthNum >= " if(!$_GET){echo 1;} else {echo ".$_GET[\"minMonth\"]. "} "
But that doesn't work for me...probably some silly PHP syntax error, I'm not sure about all the echo statements and the quotes within other quotes and whatnot.
For each of your variables do this:
$minMonth = isset($_GET["minMonth"]) ? intval($_GET["minMonth"]) : 1;
...
"WHERE sem.MonthNum >= " .minMonth. "
The intavl() call will make convert the $_GET value to an integer if it is not already, which will protect you from SQL injection security issues. If you need to do something similar with strings, use something like mysql_escape_string() instead.
You could add a variable for each, for example:
// If not set $minMonth is set to 1
$minMonth = (isset($_GET['minMonth']) ? $_GET['minMonth'] : 1);
Just do this for the other variables as well.
You can use short hand notation like Scott and David show directly in your query:
$Data = $wpdb->get_results("SELECT *
FROM database.table
WHERE sem.MonthNum >= ".(!isset($_GET['minMonth'])?'1':$_GET['minMonth'])."
AND...
You really need to sanitize the variables first though, otherwise you could be SQL injected very easily.
I'm learning PHP,MySQL and came across this function today
function get_director($director_id) {
global $db;
$query = 'SELECT
people_fullname
FROM
people
WHERE
people_id = ' . $director_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_assoc($result);
extract($row);
return $people_fullname;
}
I understand what functions are and I've created a few while learning PHP.But this one is a bit more complicated.I can't understand the
WHERE people_id = ' . $director_id
I guess the single quote ends the MySQL statement? And then it is concatenated with the argument?
Yes you are right, the single quotes end the sql string and concatenate with the supplied argument. Same case if you want to print the value out.
echo 'This is the director ID :'.$director_id;
I wouldn't call this operator an "SQL statement". And wouldn't say it is "closed" either.
For PHP it's just a string with no particular meaning.
And the quote ends this string literal, not SQL statement.
Strictly speaking here is just a concatenation, a string literal with a variable.
Having a whole complete SQL statement as a result.
The .(dot) is used for concatenation in php.
If you pass 32 to $director_id then the final query will be
select people_name from people where people_id = 32
If you pass 43 to $director_id then the final query will be
select people_name from people where people_id = 43
Means the .(dot) is used for appending the value of $director_id to the string in single quotes.
The final query will be passed to mysql. Using .(dot) is just a method in php to generate the final query that we want to execute in mysql.
I guess the single quote ends the MySQL statement?And then it is concatenated with the argument? Please help me out.
That is correct.
http://php.net/manual/en/language.operators.string.php
<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
EDIT: The meaning of the WHERE clause is best explained by the psuedo explanation of what the entire statement does.
SELECT everyone's full name WHERE their people_id is EQUAL TO some value passed into the function.
However, you are way over your head if you are evaluating these things and don't understand the basic SQL. I recommend you read the entire Tiztag PHP/MySQL tutorial.
http://www.tizag.com/mysqlTutorial/
I'm trying to insert into a database a field called Id_Obj and it's a VarChar but when I try to send it I get an error:
Unknown Column 'Id_Obj4' in 'field List'
The insert looks like this:
while($info=mysql_fetch_Array($data))
{
print "name :".$info['Id']." ";
$count=$info['Id'];
}
$t = "INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES(";
$t = $t."IdObj$count".",".$_GET["ns"];
$t = $t.")";
mysql_query($t);
The fields in the database are Id, Id_Obj, Num_Sides.
Couple of things:
You really want to make sure that
your values are escaped
You're missing out on your last ")"
in the query
Your strings need to be wrapped in
quotes, otherwise it thinks you're
using a table name
Your SQL can be like:
$t ="INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES('IdObj4','". $_GET["ns"]. "')";
Also, just as a side so you know the shortcut:
$t = $t . " something added"; is the same as $t .= " something added"
You need to wrap strings with single quotes in SQL.
$ns = intval($_GET('ns')); // This should sanitize $ns enough for the db.
if ($ns > 0)
{
$t="INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES(";
$t = $t."'IdObj4'".",".$ns . ")";
mysql_query($t);
}
You also forgot the closing parenthesis.
I have modified your code to be more resistant to SQL Injection in a very simple way. If you intend to make the Id_Obj a variable as well, you should consider using mysql_real_escape_string() to escape the value for use in your SQL statement.
When you are in a situation where your insert query is so small like this, why you don't use everything in a single line? It saves you from a lot of small problems.. I think #Mark solved your problem.