PHP script with MySQL statement with single quote - php

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/

Related

using $i var into sql query with php

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.

php variable is treated like string

I have this issue.
I need to receive, from comments column in mysql database, a string like this:
WHERE IDTable=$number
When i get this comment i have to put it like a Where clause in my query.
But if i write this code
$where=getComment($table,$field); //I get the string i wrote above
$number=5; //I initialize $number in my code
$sql="SELECT * FROM table $where";
print "SQL: $sql";
i get this:
SELECT * FROM table WHERE IDTable=$number
obviously i'd like to have in response:
SELECT * FROM table WHERE IDTable=5
How can I do that?
Thanks
I strongly suspect that the code you have a problem with is not the same code as above, as the above would not produce the result you stated. At the very least you are missing the definition of the function you're calling, to create said output.
However, what would produce such a result is by using single quotes around a string. Which prevents variable expansion, and treats them as regular strings instead.
Not only that, but your code is out of order as well. You cannot use a variable before you have declared it, as it simply does not exist yet.
The string returned by getComment() will not be parsed, so any PHP variables in it ($number) will be returned as the literal string.
I can think of two options -
1
Allow an extra parameter for getComment() so you can pass it $number
$number=5;
$where = getComment($table,$field,$number); // returns "WHERE IDTable=5"
$sql="SELECT * FROM table $where";
2
Do not return $number from getComment(), then you can add it when you build the query.
$where=getComment($table,$field); // returns "WHERE IDTable="
$number=5;
$sql="SELECT * FROM table $where $number";
Perhaps the String Value you got from MySQL: WHERE IDTable=$number may have been enclosed within Single Quotes. Consider the Example Below.
$number = 22;
$str = 'WHERE IDTable=$number';
var_dump($str); //<== YIELDS:: 'WHERE IDTable=$number' B'COS IT'S IN SINGLE QUOTES
$parts = explode("=", $str);
list($where, $var) = $parts;
$var = ltrim(trim($var), "\$");
$newStr = trim($where . "=" . $$var);
var_dump($$var); //<== YIELDS:: int 22
var_dump($newStr); //<== YIELDS:: 'WHERE IDTable=22' (length=16)
Assuming this is the case with your String; to get around that, You may simply want to extract the Variable from the String and then rebuild the String as the Snippet above demonstrates. Otherwise; if you have a possibility of enclosing the String in Double Quotes, this convoluted work-around would be utterly irrelevant.

Eval Purpose | SQL transormation?

I store my sql queries as strings and then use them later in PDO as shown below.
There is one line that I don't understand:
eval("\$query = \"$query\";");
From the docs..eval should run a string as PHP code. Why can't I just use $query directly? What does it mean to run a string of SQL?
This code works. I just don't know what eval() statement is for.
Note this is safe eval() as the input is not user defined.
"arc_id" => "SELECT id FROM credentials WHERE email=?",
"arc_id_from_hash" => "SELECT id FROM credentials WHERE pass=?",
"signin_pass" => "SELECT pass FROM credentials WHERE email=?",
"signin_validate" => "SELECT id, hash FROM credentials WHERE email=? AND pass=?"
);
public function __construct()
{
$this->db_one = parent::get();
}
public function _pdoQuery($fetchType, $queryType, $parameterArray=0) // needs review
{
$query=$this->sql_array[$queryType];
// what?
eval("\$query = \"$query\";");
// if not input parameters, no need to prep
if($parameterArray==0)
{
$pdoStatement = $this->db_one->query($query);
That code looks up the query by name, e.g. arch_id -> 'SELECT id ..', and then evaluates the query under a double-quote context in eval.
Presumable the queries could contain variables which would be interpolated. For instance, the original value might be 'SELECT id WHERE food = "$taste"' which would then then be evaluated as a double-quoted string literal in the eval and result in the interpolation of $taste so the result stored back in $query might then be 'SELECT id WHERE food = "yucky"'.
Given the data it appears to be "too clever" junk left over from a previous developer. Get rid of it. (If something similar is required in the future, although I would recommend strictly using placeholders, consider non-eval alternative mechanisms.)
eval("\$query = \"$query\";");
This is a variable replacer/templating engine.
It is replacing variables inside $query with their values.
I suggest not using eval for this, it'd probably be better to use preg_replace or str_replace.
For reference, here's a question I asked: PHP eval $a="$a"?

Returning column names from a mySQL table using PHP

Can't figure this out for the life of me. Trying to return the column names from the clients securities table, then return the result as an array. Can anybody point out where I'm getting off track?
mysql_select_db("HandlerProject", $con); //Selects database
$selectcols = "SELECT * FROM ".$clientname."securitiestable"; //selects all columns from clients security table
$tempcols = mysql_query($selectcols) or die(mysql_error());
$returnedcols = $mysql_fetch_array($tempcols);
$tempsymbol = mysql_query("SHOW COLUMNS FROM".$clientname."securitiestable");
$symbol = $mysql_fetch_array($tempsymbol);
Suggestions:
You've got $ signs prefixing the mysql_fetch_array() calls so you'd need to have assigned a value (function name you want to call) to $mysql_fetch_array (this is probably why you're seeing the error you mention in your comment).
Also you have a missing space after FROM in the second query
// v
$tempsymbol = mysql_query("SHOW COLUMNS FROM ".$clientname."securitiestable");
Last thing to check - is $clientname set?
Having said that - take Bill Karwin's advice!
I would use mysql_fetch_assoc() for the SELECT query, and then call array_keys() on any row of the result.
$selectcols = "SELECT * FROM ".$clientname."securitiestable";
$tempcols = mysql_query($selectcols) or die(mysql_error());
$returnedcols = mysql_fetch_assoc($tempcols);
$colnames = array_keys($returnedcols);
Your fatal error is because of a separate issue: you have a $ symbol at the start of your function call. This is legal PHP syntax, because you can put the name of a function in a variable and call it indirectly:
function foo($arg)
{
echo $arg . "!\n";
}
$bar = "foo";
$bar("hello world");
But in your case, it's probably not what you intended. If you want to call a function by its literal name, don't put a $ in front of it. If you have a string variable that contains the name of a function, then you can use the variable as I show above.

MySQL Query in CodeIgniter with Session ID

Let's say I have a query:
" SELECT * FROM table
WHERE donor_id = " .$this->session->userdata('id') ."
GROUP BY rating"
However, it appears that I get a mysql syntax error here, citing that $this->session->userdata('id') gives me '25' for example, instead of 25. Are there any workarounds here to prevent $this->session->userdata('id') from being quoted?
Thanks.
In CI, I do this all the time:
$id = intval($this->session->userdata('id'));
$sql = " SELECT * ".
" FROM table ".
" WHERE donor_id = {$id} ".
"GROUP BY rating ";
//process $sql below
Creating query like this will make you easier to spot bug and prevent SQL injection. Use concatenation when you need to split query to multiple lines instead of make it a long multiple string is to prevent the actual query string got too long. Indent the SQL keyword is to make it easier spot logical and syntax bug.
intval($this->session->userdata('id'))
Assuming you mean that it is returning you a string instead of an integer you could always try using settype or intval:
$var = '2';
settype($var, "integer");
$var = intval($var);
However, if you mean that the quotes are for some reason hard-coded in, you could do a string replace, if you are sure that the value will not contain quotes:
ech str_replace("'", "", "'2'"); // prints 2

Categories