I am writing a query that gets an ID from the database where it's last digit can be 1-5. This works but seems messy. Is there a cleaner way of doing this?
$id1 = $id.'1';
$id2 = $id.'2';
$id3 = $id.'3';
$id4 = $id.'4';
$id5 = $id.'5';
$sql = "SELECT col1
FROM table1
WHERE id = :id1 OR id = :id2 OR id = :id3 OR id = :id4 OR id = :id5
LIMIT 1";
$core = Connect::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindParam(':id1', $id1, PDO::PARAM_STR);
$stmt->bindParam(':id2', $id2, PDO::PARAM_STR);
$stmt->bindParam(':id3', $id3, PDO::PARAM_STR);
$stmt->bindParam(':id4', $id4, PDO::PARAM_STR);
$stmt->bindParam(':id5', $id5, PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetchAll();
Try This
$sql = "SELECT col1
FROM table1
WHERE id = :id1 OR id = :id2 OR id = :id3 OR id = :id4 OR id = :id5
LIMIT 1";
$core = Connect::getInstance();
$stmt = $core->dbh->prepare($sql);
for($i; $i<=5; $i++){
$stmt->bindParam(':id'.$i, $id.$i, PDO::PARAM_STR);
}
$stmt->execute();
$data = $stmt->fetchAll();
Another alternative would be to use question mark placeholders. All the values, just load em all up inside the ->execute method:
Question mark placeholders:
$sql = "SELECT col1
FROM table1
WHERE id = ? OR id = ? OR id = ? OR id = ? OR id = ?
LIMIT 1";
Inside execute:
$stmt->execute(array($id1, $id2, $id3, $id4, $id5));
Related
I have a SQL query that is based on user input.
However, in the table, theres a "-1" at the end of every word that you search for.
For example if you want to get the sql result of car, it's actually named car-1 in the database, but the user should only be able to search for car.
This is how its setup:
$sql = "SELECT * FROM that WHERE this = ?";
$stmt = $conn->prepare($sql);
$search_query = $_POST['this'];
$stmt->bind_param('s', $search_query);
$stmt->execute();
$result = $stmt->get_result();
What I want, is that the select query should be like:
$sql = "SELECT * FROM that WHERE this = ? + '-1'";
But ^^ doesn't work.
$sql = "SELECT * FROM test WHERE NAME='car' & -1";
test = that
NAME= table name
'car' = this
Why don't you just concat -1 to search_query :
$sql = "SELECT * FROM that WHERE this = ?";
$stmt = $conn->prepare($sql);
$search_query = $_POST['this'];
$stmt->bind_param('s', $search_query.'-1');
$stmt->execute();
$result = $stmt->get_result();
Using MySQL:
$sql = "SELECT * FROM that WHERE this = CONCAT(?, '-1')";
Using PHP:
$stmt->bind_param('s', $search_query . "-1");
Normally i use this code, it's work good.
<?PHP
include("connect.php");
$xxx = "275";
$sql = 'SELECT * FROM test_table WHERE number <= ? order by id desc';
$statement = $db_mysqli->prepare($sql);
$statement->bind_param('s', $xxx);
$statement->execute();
$result = $statement->get_result();
$row = $result->fetch_array(MYSQLI_ASSOC);
$number = $row['number'];
echo $total_price;
?>
Then i apply code by use php var for select table. like this
<?PHP
include("connect.php");
$xxx = "275";
$table_name = "test_table";
$sql = 'SELECT * FROM ? WHERE number <= ? order by id desc';
$statement = $db_mysqli->prepare($sql);
$statement->bind_param('ss', $table_name , $xxx);
$statement->execute();
$result = $statement->get_result();
$row = $result->fetch_array(MYSQLI_ASSOC);
$number = $row['number'];
echo $total_price;
?>
But not get any data, how can i do ?
You cannot bind to a table name. You will need to write your code as:
$table_name = "test_table";
$sql = "SELECT * FROM $table_name WHERE number <= ? order by id desc";
$statement = $db_mysqli->prepare($sql);
$statement->bind_param('s', $xxx);
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);
When I execute this query to the DB:
SELECT * FROM `task` WHERE `date_time_from` like '%0000%'
I get a few results, now I am trying to do the same with PDO and I can not manage to get any results or errors. This is what I have done:
$dbChain = 'mysql:host='.$GLOBALS['dbhost'].';dbname='.$GLOBALS['dbname'];
try{
$dbh = new PDO($dbChain, $GLOBALS['dbuser'], $GLOBALS['dbpassword']);
$sql = "SELECT * FROM task"
. "WHERE date_time_from like CONCAT('%', :dateFrom, '%')";
$a = '0000';
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':dateFrom', $a);
$stmt->execute();
$total = $stmt->rowCount();
echo $total;
while ($row = $stmt->fetch()){
var_dump($row);
}
} catch (Exception $e){
echo 'Error'.$e->getMessage();
}
The result of this is $total = 0. Can anyone tell me what am I doing wrong?
I have also tried this:
$sql = "SELECT * FROM task"
. "WHERE date_time_from like :dateFrom";
$a = "%0000%";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':dateFrom', $a);
$stmt->execute();
Same result for $total.
bindParam escapes the "%" in the query. It will not work as you expect...
You can, however, use bindValue like so...
$sql = "SELECT * FROM task WHERE date_time_from LIKE ?";
$stmt = $dbh->prepare($sql);
$stmt->bindValue( 1, "%0000%" );
$stmt->execute();
Alternatively, if you want 0 values from a datetime column, you can just do this:
$sql = "SELECT * FROM task WHERE date_time_from = '0000-00-00'";
here is my mysql code and equivalent pdo code i need to know what is wrong
$id = $_POST['id'];
$query1=mysql_query("SELECT Quantity,id FROM `yumyum`.`food` where `food`.`id` LIKE $id");
$r = array();
while($r = mysql_fetch_assoc($query1)) {
$output = $r['Quantity'];
echo $output;
$query2=mysql_query("UPDATE food SET Quantity = Quantity - 1 where `food`.`id` LIKE ".$r["id"]);
PDO code
$stmt = $db->prepare("SELECT * FROM yuymuym WHERE id=:id AND Quantity=:Quantity");
$stmt->execute(array($id, $Quantity));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC)
How about this. I don't know what $_POST['id'] is so you have to figure the rest youself. It updates every item with id in $ids array. So this updates items with id 1,2,3,4 and 5.
$db = new PDO('mysql:host=localhost;dbname=yumyum', 'username_here', 'password_here');
$ids = array(1,2,3,4,5);
foreach($ids as $id){
$stmt = $db->prepare("SELECT Quantity, id FROM `food` WHERE `food`.`id` = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch();
if($row){
//uncomment to see $row content
//var_dump($row);
$rowId = (int)$row['id'];
$rowQuantity = (int)$row['Quantity'];
echo $rowQuantity;
$ustmt = $db->prepare("UPDATE `food` SET `Quantity` = `Quantity` - 1 WHERE `food`.`id` = :id");
$ustmt->bindParam(':id',$rowId);
$ustmt->execute();
}else{
var_dump($stmt->errorInfo());
}
}
But PDO basics:
Query (Works with select, insert, update, everything else):
$id = (int)$_POST['id'];
$else = $_POST['string'];
// Connect to database
$db = new PDO('mysql:host=HOST_HERE;dbname=DATABASENAME_HERE', 'USERNAME_HERE', 'PASSWORD_HERE');
// First we prepare our query
$stmt = $db->prepare("... WHERE `id` = :id AND `something` = :else");
// We bind values to our prepared query
$stmt->bindParam(':id',$id);
$stmt->bindParam(':else',$else);
// We execute our query
$success = $stmt->execute();
// If we want to fetch only one row:
$row = $stmt->fetch();
echo $row['id'];
// If we want to fetch all rows:
$rows = $stmt->fetchAll();
foreach($rows as $row){
echo $row['id'];
}
These are very basics, if you don't understand what is really happening here, you should learn some more.