MySQL Query in CodeIgniter with Session ID - php

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

Related

Variable mysql statement in php

I have a variable that is a filter for my query:
$filterString.=" AND venue = ".$venue;
And I want this variable (when called) to add the AND filter statement to my query.
My query is as follows (with the failed attempt):
mysql_query("SELECT * FROM event
WHERE city = '$city' " . $filterString . "
ORDER BY date ASC");
I think the venue needs to be surrounded by single quotes:
$filterString.=" AND venue = '".$venue.".";
However, it is better to use parameterized queries, instead of embedding queries directly in the SQL string.
You could use:
$filterString .= !empty($venue) ? " AND venue = '$venue'" : '';
Substitute whatever test you want at the start, the idea is to return a blank string if $venue doesn't apply to the filter.
To answer your other comment question:
WHERE 1
is a valid condition that works like Anything

Basic PHP - Conditional Concatenation Within SQL Query

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.

Session variable is not working in MySQL statement

I am trying to use session variable($_SESSION['asc_id'], which holds some value like "AS0027001") in an SQL statement, but it is not working.
When I hardcode the value, it is providing results.
Can anyone please correct me.
MySQL query which is not working
$asc_id = $_SESSION['asc_id'];
$rs = mysql_query('select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = "$asc_id"
and lname_fname_dob like "' .
mysql_real_escape_string($_REQUEST['term']) .
'%" order by lname_fname_dob asc limit 0,10', $dblink);
Mysql query which is working
$rs = mysql_query('select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = "AS0027001" and lname_fname_dob like "' .
mysql_real_escape_string($_REQUEST['term']) .
'%" order by lname_fname_dob asc limit 0,10', $dblink);
Variable substitution only works within double quoted strings, not single quoted ones. In other words, you should do;
$rs = mysql_query("select .... and asc_id = '$asc_id' and ... limit 0,10", $dblink);
Btw, you did make sure the value doesn't include any characters that may lead to SQL injection, right? Otherwise you should use mysql_real_escape_string to make sure before inserting it into a query.
When you print the strings, it will be clear. When the question is reformatted to leave the SQL readable, the problem is clear. (The first rule for debugging SQL statements is "print the string". A second rule, that makes it easier to comply with the first, is always put the SQL statements into a string which you pass to the SQL function.)
You use the . notation to embed the request term in the string; you don't use that to embed the $asc_id into the string. You should also use mysql_real_escape_string() on the session ID value to prevent SQL injection.
First print the variable $asc_id . If it displays nothing, session is unavailable . In that case you missed session_start() in top of the current executing page .
From the SQL query, you cannot replace the value of a variable inside single quoted string .
Use . symbol for mixing string value with variable or use double quoted string . I prefer first one .
For troubleshooting , simplest method is printing variable values. From the result , you will understand what is missing .
Thanks
Try this. from the comment you added, I modified it like this
session_start(); //add this if you did not do it yet
$asc_id = $_SESSION['asc_id'];
$rs = mysql_query("select asc_lastname, asc_firstname, asc_middlename, lname_fname_dob
from issio_asc_workers where asc_user_type = 31
and asc_id = '$asc_id'
and lname_fname_dob like '".
mysql_real_escape_string($_REQUEST['term']) .
"%' order by lname_fname_dob asc limit 0,10", $dblink);

PHP script with MySQL statement with single quote

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/

Database insert in PHP returns string not defined and notice about unknown column

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.

Categories