In zend, how to print a mysql query properly? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to print exact sql query in zend framework ?
In zend profiler, I can only either print the query with question markers (getQuery) or print the parameter array (getQueryParams).
Is there a way to replace all question markers, and print the real sql query?
Thanks!

Something like that should work:
$profile = $this->getQueryProfile($queryId);
$query = $profile->getQuery();
$params = $profile->getQueryParams();
foreach ($params as $par) {
$query = preg_replace('/\\?/', "'" . $par . "'", $query, 1);
}

The framework uses prepared statements so actually this is the real query - in reality its send to the database which parses it and then the params are binded to it and executed.

You can use the __toString() method.
$dbTable = new Application_Model_DbTable_TradeshowBooking();
$select = $dbTable->select();
$select->setIntegrityCheck(false);
$select->where('ends_on + INTERVAL 4 WEEK > ? ', $requestParams['ends_on']);
Zend_Registry::get('logger')->log($select->__toString(), Zend_Log::INFO);

Related

Using str_replace in table query in MYSQL [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
If you create a variable inside a if statement is it available outside the if statement?
(4 answers)
How to replace "if" statement with a ternary operator ( ? : )?
(16 answers)
If variable equals value php [duplicate]
(4 answers)
Closed 2 years ago.
There are a lot of examples on SO of using str_replace to modify a query that uses variables in MYSQL but I can't find one that solves my problem.
I have the following legacy query that I'm debugging written in PHP and MySQL.
Somewhat simplified it is:
$sql = "SELECT * from MOVIES WHERE cat = '$cat'";
In the event that cat has a certain value, say, "action" I want to check for "adventure";
Let's say you start with query:
$cat = "action";
$sql = "SELECT * FROM MOVIES WHERE cat='$cat'";
I'm trying to modify the query with:
$needle = "cat=".$cat;
$altcat = "adventure";
$altwhere = "cat=".altcat;
$sql = str_replace($needle,$altwhere,$sql); //NOTHING GETS REPLACED...NOT MATCHING Needle
How can I do this? I'm thinking the problem has something to do with use of spaces or apostrophes in the sql string but can't get it to work.
Thanks for any suggestions.
You want to replace "cat='".$cat."'" with "cat='adventure'", not "cat=".$cat with "cat=adventure".
(Though you are inconsistent in saying if there are spaces around the =.)
But you should not do this and should use a placeholder instead.
I would not try to do string substitution on the SQL query. Instead, just use query parameters.
$cat = 'action'; // suppose this is the input to your program
$sql = "SELECT * from MOVIES WHERE cat = ?";
if ($cat == 'action') {
$cat = 'adventure';
}
$stmt = $db->prepare($sql);
$stmt->execute( [ $cat ] );

PHP Query not working with the function I made for it [duplicate]

This question already has answers here:
How to avoid code repetition with PHP SQL prepared statements?
(2 answers)
Closed 2 years ago.
I'm trying to make a database for users to publish scripts for a game. Every single time I've had an issue using query and got it working one way or another. This time, I decided to make it a little easier to format the string for the query. Its not working. Heres my code:
function getSQLOperation($Data){
$returning = "INSERT INTO `ScriptDatabase`";
$keys = "(";
$values = ") VALUES (";
foreach ($Data as $Key => $Value){
$keys = $keys."`".$Key."`, ";
$values = $values."'".$Value."',";
}
return $returning.$keys.$values.")";
}
$values = array();
$values['Visibility'] = "Public";
$values['Name'] = "NameOfScript";
$values['Publisher'] = "UserID";
$values['Genres'] = "";
$values['PublishDate'] = Date('m-d-Y');
$values['Updated'] = $values['PublishDate'];
$values['Version'] = "1.0";
$values['Description'] = "None for now";
$values['Likes'] = "0";
$values['Dislikes'] = "0";
$values['Downloads'] = "0";
$operation = getSQLOperation($values);
mySQL table structure:
Anything I'm doing wrong here?
MySQL doesn't allow trailing commas in queries, but your query is generated as:
INSERT INTO `foo`(`bar`, `baz`,) VALUES ('x','y',)
Of note, there are much better ways to work with MySQL. Check out PDO, especially prepared statements.
I mean it. Your query is vulnerable to SQL Injection attack and that's serious.

Adding backslash before quotes when string contains them - PHP [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 6 years ago.
I'm doing a little ajax question-result system. When user types something into the textarea, the result is automatically searched and outputted.
Problem is that every time user types the question that contains "" or '' - the search is unsuccessful. Is there any way I can add backslash to "" or '' inside the string, so it'd be ignored?
Or is there any filter that ignores the "" or ''?
I need the question to be searched with quotes, because questions in database contains them.
Here's the code:
$q = $_POST['q'];
// for every " or ' in $q add \ before it
$results = array();
$result = array();
$count = 0;
$stmt = $dbh->prepare("SELECT result FROM quest WHERE quest LIKE '".$q."%'");
if($stmt->execute()){
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
$count= $stmt->rowCount();
}
if($result != NULL){
foreach($result as $part){
foreach($part as $item){
$results[] = $item;
}
}
echo htmlentities($results[0], ENT_QUOTES, "UTF-8");
}
You are not using prepared statements correctly, and that's why you are having this issue. If you use prepared statements correctly, they solve this issue for you. The docs for this are actually pretty good.
http://php.net/manual/en/pdo.prepared-statements.php
EDIT: Please take the time to learn how to use them correctly. If not, your code is susceptible to SQL injection.
Try using addslashes() Function

SQL IN not working when ran from php [duplicate]

This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
MySQLi Bind Param with an array for IN [duplicate]
(2 answers)
Closed 9 years ago.
I'm trying to write code that basically finds your facebook friends that are on my website. I succeed in phpmyadmin running the query but for some reason when i try to run the code from php it doesn't work
Here's the php code. Whenever i take the $string echo and place it in mysql it works just fine, but for whatever reason when running it in php the query is not returning any results.
$fql = "SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = 100000903067831) AND is_app_user = 'true'";
$param = array(
'method' => 'fql.query',
'query' => $fql
);
$this->load->library('facebook');
echo $this->facebook->getLoginUrl();
$fqlResult = $this->facebook->api($param);
$userIDarray = array();
foreach($fqlResult as $result)
{
echo $result['uid']."<br>";
array_push($userIDarray, intval($result['uid']));
}
$string = implode(', ',$userIDarray);
echo $string;
$vars = array($string);
$query = $this->db->query("SELECT * FROM users WHERE users.facebook_id IN (?)", $vars);
echo var_dump($query);
foreach($query->result() as $data)
{
echo var_dump($data);
}
You cannot pass multiple parameters in a single ?.
You need to construct the options for IN yourself using concatenation.
Like so:
foreach($fqlResult as $result)
{
echo $result['uid']."<br>";
array_push($userIDarray, intval($result['uid']));
}
$string = implode(', ',$userIDarray);
$query = $this->db->query("SELECT * FROM users WHERE users.facebook_id
IN ('.$string.')");
Note that you need to make sure your items in the $userIDarray are properly escaped.
Because you're not using parameters, but you've injected these values into your SQL you are in danger of SQL injection attacks.
You are passing them through intval which guarantees that the strings will only contain 0..9 and - so you are safe from that here.
If the data is not numeric, you need use mysqli_real_escape_string to compensate for the fact that you're bypassing PDO's parameters.

How to protect sql query when a php variable is empty [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to prevent SQL injection in PHP?
I have a following MySQL query :
if($obj->{'parentId'} == null){
$parentID = 'NULL';
} else{
$parentID = $obj->{'parentId'};
}
$q = 'UPDATE tasks SET
Name = "'.$obj->{'Name'}.'",
Cls = "'.$obj->{'Cls'}.'",
parentId = '.$parentID.',
PhantomId = '.$obj->{'PhantomId'}.',
PhantomParentId = '.$obj->{'PhantomParentId'}.',
leaf = "'.$leaf.'" WHERE Id = "'.$obj->{'Id'}.'"';
The problem is, that if any of my non-string values is empty, the whole query throws error. How can I fix it crashing when for example $obj->{'PhantomId'} is empty without any aditional libs ?
Better consider to opt out to bound parameters. But if you still want to construct SQL queries use conditions
$q = "UPDATE ...";
...
if (!empty($obj->{'PhantomId'})) {
$q .= ", PhantomId = '" . $obj->{'PhantomId'}. "'";
}
...

Categories