Step by step MySql query to PDO - php

I'm trying to figure out how can I build a query in PDO like this one
//...
$sql = array();
$sql[] = "SELECT * FROM `posts` WHERE `completed` = '1'";
if($this->is($_GET, 'category')) {
$sql['category'] = "AND `category` = '".$_GET['category']."'";
}
if($this->is($_GET, 'tags')) {
$sql['tags'] = "AND `tags` LIKE '%".$_GET['tags']."%'";
}
$sql[] = "ORDER BY `id` DESC LIMIT ".$offset.", ".$rows_per_page;
$query = $this->query(implode(" ", $sql));
//...
I tried something like that..
$sql = array();
$sql[] = "SELECT * FROM `posts` WHERE `completed` = :completed";
if($this->is($_GET, 'category')) {
$sql['category'] = "AND `category` = :category";
}
$sql[] = "LIMIT 0, 5";
$this->db->query(implode(" ", $sql));
$this->db->bind(array(
':completed' => 1,
':category' => $this->is($_GET, 'category')
));
$fetch = $this->db->fetchAll();
print_r($fetch);
but there's a error that says I can not bind nonexistent variables "SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens"
...and with some research I figure out I can not bind before query
..so.. do you have any idea how can I do this?

Related

get result of query step by step codeigniter

I need to do something like this:
if (isset($account)) {
$this->db->where('account', $account);
}
if (isset($subject)) {
$this->db->where('subject', $subject);
}
if (isset($contact)) {
$this->db->where('_from', $contact);
}
//here i need to get result
$resul1 = $this->db->get('table');
$limit = 5; $offset =10;
$this->db->limit($limit, $offset);
//here i need to get result with offset and limit
$result2 = $this->db->get('table');
$result1 should execute this query
SELECT *
FROM `table`
WHERE `account` = 'some account'
AND `subject` = 'some subject'
AND `_from` = 'name'
and $result2 should execute this query ($query1 + offset and limit):
SELECT *
FROM `table`
WHERE `account` = 'some account'
AND `subject` = 'some subject'
AND `_from` = 'name'
LIMIT 10, 5
but $result2 execute as a separate query: select * FROM table LIMIT10, 5
is it possible to achieve this or I need to start the query from the begining?
LIMIT Without limit() Function
result = $this->db->get('table', 0, $offset);
Or using manual select:
$query = "SELECT *, COUNT(account) AS total FROM `table` WHERE `account` = ? AND `subject` = ? AND `_from` = ? LIMIT 0, ?";
$result = $this->db->query($query, array($account, $subject, $contact, $offset));

Use PDO exec(array()) with several operands

I would like to secure my requests in my code.
Today my curent functions are like this.
public function UpdatePMS($table,$data,$where) {
$ret = array();
$set_data = "";
foreach($data as $key => $value){
$set_data .= $key."= '".$value."', ";
}
if (isset($where)) {
$where = "WHERE ".$where;
}
$sql = "UPDATE ".$table." SET ".$set_data."".$where;
$sql = str_replace(", WHERE", " WHERE", $sql);
$stm = $this->db->prepare($sql);
$ret = $stm->execute();
return $ret;
}
With this way, i can select any tables, any datas, and any conditions.
For example:
WHERE id = 1 and status < 10
Or only
WHERE id = 10
Or sometimes
WHERE id = 1 and status >= 5
The content of where could change.
A kind of universal request.
Same for Delete, Update, Select, insert.
I tried to do like this, but it doesn't work.
$db = new PDO('mysql:host=localhost;dbname=asterisk','root','');
$table = "my_table";
$where = "WHERE id = 1";
$sql = 'SELECT * FROM :table :where';
$stm = $db->prepare($sql);
$stm->execute(array(":table" => $table, ":where" => $where));
$ret = $stm->fetchall(PDO::FETCH_ASSOC);
Any ideas?
Frankly, you cannot use prepared statements this way. There are rules to follow. So it just makes no sense to write something like this
$table = "my_table";
$where = "WHERE id = 1";
$sql = 'SELECT * FROM :table :where';
$stm = $db->prepare($sql);
$stm->execute(array(":table" => $table, ":where" => $where));
instead you should write this code
$sql = 'SELECT * FROM my_table WHERE id = ?';
$stm = $db->prepare($sql);
$stm->execute(array($id));
Besides, you cannot parameterize table and field names, so it's better to write them as is.
so i need to make one function per different requests, right?
Honestly - yes. It will spare you from A LOT of headaches.
public function UpdatePMS($data, $id)
{
$data[] = $id;
$sql = "UPDATE table SET f1 = ?, f2 = ? WHERE id = ?";
$stm = $this->db->prepare($sql);
$ret = $stm->execute($data);
return $ret;
}
which is going to be used like
$obj->UpdatePMS([$f1, $f2], $id);

How to create multiple search?

try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
} else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
i need to do multiple search, with first_name,last_name,middle_name,contact_no1 fields
If you want to do search with all fields add fields in WHERE with OR:
try {
$keyword = trim($_GET["keyword"]);
if ($keyword <> "" ) {
$sql = "SELECT * FROM tbl_contacts WHERE 1 AND "
. " (first_name LIKE :keyword OR last_name LIKE :keyword OR middle_name LIKE :keyword OR contact_no1 LIKE :keyword) ORDER BY first_name ";
$stmt = $DB->prepare($sql);
$stmt->bindValue(":keyword", $keyword."%");
} else {
$sql = "SELECT * FROM tbl_contacts WHERE 1 ORDER BY first_name ";
$stmt = $DB->prepare($sql);
}
public function search($requestArray){
$sql = "";
if( isset($requestArray['firstname']) && isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE AND (`first_name` LIKE '%".$requestArray['search']."%' OR `last_name` LIKE '%".$requestArray['search']."%')";
if(isset($requestArray['firstname']) && !isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE `first_name` LIKE '%".$requestArray['search']."%'";
if(!isset($requestArray['firstname']) && isset($requestArray['lastname']) ) $sql = "SELECT * FROM `tbl_contacts` WHERE `last_name` LIKE '%".$requestArray['search']."%'";
$STH = $this->DBH->query($sql);
$STH->setFetchMode(PDO::FETCH_OBJ);
$someData = $STH->fetchAll();
return $someData;
}
I used this method in one of my project for searching with two field hope it could help you. where $requestArray will get the data from form and 'firstname' , 'lastname' are two key of the array which you will enter your searchbox and submit to search. I just showed you here the query style and before that you have tor trim the values.

How to loop php using ref data from mysql?

How to loop php using ref data from mysql ?
work flow :
Loop If column 'xxx' == ''
{
$sql = "SELECT * FROM table WHERE xxx == '' order by id desc";
$result = mysql_query($sql);
$datas=mysql_fetch_array($result);{
$id = stripslashes(str_replace('\r\n', '<br>',($datas['id'])));
}
$sql = "UPDATE table SET xxx = 'test' WHERE id = '$id' ";
$dbQuery = mysql_query($sql);'
}
ypur query is confusing. why would you store ids with html in them? regardless, this should work
$sql = "SELECT * FROM table WHERE xxx != '' "; //ORDER BY will not work since ids are not int
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result){
$id = stripslashes(str_replace('\r\n', '<br>',($row['id'])));
$sql = "UPDATE table SET xxx = 'test' WHERE id = '$id' ";
$dbQuery = mysql_query($sql);'
}

if argument inside mysql query

I have now three different PHP pages that contain almost the same information so to be able to reduce this to one page I need to have a php variable inside the mysql query.
Today it is like this:
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY yearstart DESC, mndstart DESC";`
I need that the " AND Bruk = '1'" is removed from this query-line if i put ?nobruk=no in the adressbar. Is this possible and if so, how?
You don't want to (and can't) put an if inside your query; you want to use an if to create your query based on some condition. There are lots of ways to write this, one of which is
if (!empty($_GET['nobruk'])) {
$query1 = "SELECT ... WHERE `Kategori` = '1' ORDER BY ...";
}
else {
$query1 = "SELECT ... WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY ...";
}
Another way, which is shorter and involves the ternary operator, is
$includeBruk = empty($_GET['nobruk']);
$query1 = "SELECT ... WHERE `Kategori` = '1' ".
($includeBruk ? "AND `Bruk` = '1' " : "").
"ORDER BY ...";
A simple if statement:
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori` = '1'";
if ($_GET['nobruk']!='no') {
$query1.=" AND `Bruk` = '1'";
}
$query1.= " ORDER BY yearstart DESC, mndstart DESC";
Like this :
<?php
$query = ($_REQUEST['nobruk'] == "no") ? "SELECT * FROM `Yrker` WHERE `Kategori` = '1' ORDER BY yearstart DESC, mndstart DESC": "SELECT * FROM `Yrker` WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY yearstart DESC, mndstart DESC";
echo $query;
?>
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori`='1' ".($_GET['nobruk'] === 'no' ? "" : "AND `Bruk`='1' ")."ORDER BY yearstart DESC, mndstart DESC";

Categories