please How to convert mysql query to pdo in my code? - php

my code PHP in mySQLquery to unique product id function
function kode($tabel, $inisial){
$struktur = mysql_query("SELECT * FROM $tabel");
$field = mysql_field_name($struktur,0);
$panjang = mysql_field_len($struktur,0);
$qry = mysql_query("SELECT MAX(".$field.") FROM ".$tabel);
$row = mysql_fetch_array($qry);
if ($row[0]=="") {
$angka=0;
}
else {
$angka = substr($row[0], strlen($inisial));
}
$angka++;
$angka =strval($angka);
$tmp ="";
for($i=1; $i<=($panjang-strlen($inisial)-strlen($angka)); $i++) {
$tmp=$tmp."0";
}
return $inisial.$tmp.$angka; }
how to convert this code to php pdo? please help me..

Here is a standard snippet I use for PDO:
try
{
$dbh = new PDO("mysql:host=xxxxxxxxxxxx;dbname=streaming", "xxxx", "xxxx");
}
catch (Exception $e)
{
throw new Exception( 'Something really gone wrong', 0, $e);
}
$date = reformatDate($_POST['date']);
$sql="SELECT * FROM order_items WHERE date_start = :date";
$sth = $dbh->prepare($sql);
$sth->bindParam(':date', $date, PDO::PARAM_STR, 10);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
This example should point you in the right direction, but you need to do the heavy lifting.
Update
This would also be acceptable.
$madeupstring = "Mk9285425";
$sql="SELECT * FROM order_items WHERE product = :whatever";
$sth = $dbh->prepare($sql);
$sth->bindParam(':whatever', $madeupstring);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
You could also do this:
$sql="SELECT * FROM order_items WHERE product = 'Mk9285425'";
$sth = $dbh->prepare($sql);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

Related

I want to write code for check if data already exits then insert in different table

I already write the code to check if table call hm2_history type = commission if yes then insert data into table call hm2_deposit, when I test echo was correct and show the result is :
Connected successfully
354
368
But won't insert into hm2_deposit , I don't know how to adjust it i have a little bit knowledge about php
This is my code
<?php
$servername = "localhost";
$username = "tinybaht_findroom";
$password = "212224";
function setChecked($conn,$params){
$s = $conn->prepare("UPDATE `hm2_history`
SET history_ref_id=-1
WHERE id=:id
");
$s->execute($params);
}
try {
$conn = new PDO("mysql:host=$servername;dbname=tinybaht_findroom", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare("SELECT * FROM hm2_history");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$a = $stmt->fetchAll();
$plans = array();
foreach($a as $i){
$plans[$i['type']] = 'commissions';
}
$stmt = $conn->prepare("SELECT * FROM hm2_history WHERE id NOT IN(SELECT ref_id FROM hm2_deposits WHERE ref_id > 0) AND type='commissions'");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll();
foreach($rows as $k=>$v) {
$plan_type = isset($plans)?:'';
$m = $v['type'];
if (!empty($plan_type)){
echo '<br>'.$v['id'];
if ($m = "commissions" ){
setChecked($conn,array('id'=>$v['id']));
continue;
}
}else{
setChecked($conn,array('id'=>$v['id']));
continue;
}
//deposits
$s = $conn->prepare("INSERT INTO `hm2_deposits`
SET `user_id`=:user_id,
`type_id`=:type_id,
`deposit_date`=:deposit_date,
`last_pay_date`=:last_pay_date,
`status`=:status,
`q_pays`=:q_pays,
`amount`=:amount,
`actual_amount`=:actual_amount,
`ec`=:ec,
`compound`=:compound,
`dde`=:dde,
`unit_amount`=:unit_amount,
`bonus_flag`=:bonus_flag,
`init_amount`=:init_amount,
`ref_id`=:ref_id
");
$v['ref_id'] = $v['id'];
$v['amount'] = $v['amount']*$rate;
$v['actual_amount'] = $v['actual_amount']*$rate;
$v['init_amount'] = $v['init_amount']*$rate;
$v['bonus_flag'] = 1;
$v['type_id']= 9;
unset($v['id']);
$s->execute($v);
$lastDepositId = $conn->lastInsertId();
$date = date('Y-m-d H:i:s');
}
?>
this is photo of my db table name is hm2_deposits hm2_deposits
this is photo of my db table name is hm2_history enter image description here
There is an error in your SQL:
$s = $conn->prepare("INSERT INTO hm2_deposits
SET user_id=:user_id,
type_id=:type_id,
deposit_date=:deposit_date,
last_pay_date=:last_pay_date,
status=:status,
q_pays=:q_pays,
amount=:amount,
actual_amount=:actual_amount,
ec=:ec,
compound=:compound,
dde=:dde,
unit_amount=:unit_amount,
bonus_flag=:bonus_flag,
init_amount=:init_amount,
ref_id=:ref_id
");
Read the proper way to do it at:
https://www.w3schools.com/sql/sql_insert.asp

SQL request dont work as expected

i have a PHP REST API, i did this function to get services with a certain idpro or idclient
function getServices($request) {
require_once 'db.php';
$emp = json_decode($request->getBody());
$id = $request->getAttribute("id");
$sql = "select * FROM service WHERE idpro=:idpro OR idclient= :idclient ORDER BY date_debut DESC";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("idpro", $id);
$stmt->bindParam("idclient", $id);
$stmt->execute();
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
return json_encode( $wines);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
I have in my database a row with idpro=40 and idclient=30 when i execute this function with id=40 in get the disered result but when i execute it with id=30 i dont get anything, i tried to execute this line in PHPMYADMIN: select * FROM service WHERE idpro=30 OR idclient= 30 and it worked as expected
$sql = "select * FROM service WHERE idpro=:idpro OR idclient=:idclient ORDER BY date_debut DESC";
You mentioned that it worked with idpro and it has no space between the parameter and value so try and remove the space between idclient= :idclient to see if thats the issue. Since it works when you execute the line I assume that its how it is syntactically called.
OR
Try using one parameter for the value. Change like this:
function getServices($request) {
require_once 'db.php';
$emp = json_decode($request->getBody());
$id = $request->getAttribute("id");
$sql = "select * FROM service WHERE idpro=:myID OR idclient= :myID ORDER BY date_debut DESC";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("myID", $id);
$stmt->execute();
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
return json_encode( $wines);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

PDO Limit Query Not Working using Binding in Execute

I'm trying to get a limit query working. So far I've verified the following:
All input it valid and correct.
The Query works when manually run against MySQL
The Values are Cast to INT. I have even replcated the variables with the int value.
try {
$sql = "SELECT * FROM sensor_data WHERE sid=:sid ORDER BY id DESC LIMIT :starting_limit, :recordlimit";
$core = CoreDB::getInstance();
$sth = $core->dbh->prepare($sql);
$sth->execute(array(':sid' => $sensor->getID(), ':starting_limit' => (int)0, ':recordlimit' => (int)10));
// $sth->execute(array(':sid' => $sensor->getID()));
$results = $sth->fetchAll();
var_dump($sth->rowCount());
if ($sth->rowCount() > 0) {
foreach($results as $row){
$id = $row['id'];
var_dump($id);
}
}
}
catch(Exception $e){
}
Any advice is appreciated
The only solution I've found is to manually bind params rather than put them in an array in the execute method.
try {
$sql = "SELECT * FROM sensor_data WHERE sid=:sid ORDER BY id DESC LIMIT :starting_limit, :recordlimit";
$core = CoreDB::getInstance();
$sth = $core->dbh->prepare($sql);
$sth->bindValue(':sid', $sensor->getID(), PDO::PARAM_INT);
$sth->bindValue(':starting_limit', 0, PDO::PARAM_INT);
$sth->bindValue(':recordlimit', 10, PDO::PARAM_INT);
$sth->execute();
$results = $sth->fetchAll();
var_dump($sth->rowCount());
if ($sth->rowCount() > 0) {
foreach($results as $row){
$id = $row['id'];
var_dump($id);
}
}
}
catch(Exception $e){
}
If anyone is aware of how to get it working in the execute method please let me know and I will update the answer.

In a mysql transaction, can $pdo handle be used for multiple queries or just once?

I want to begin a transaction with multiple queries in MySQL and through self-learning, I write my code like:
$pdo = new PDO('mysql:host=localhost;dbname=project', '', '', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
));
$pdo->beginTransaction();
try {
// First Query
$sql = "SELECT * FROM table1 WHERE table1.id = 1";
$stmt = $pdo->prepare($sql);
$stmt->execute();
if ($row = $stmt->fetch()) {
// There should be only one row so I used if
}
else {
}
// Second Query
$sql2 = "SELECT * FROM table2 WHERE table2.id = 1";
$stmt2 = $pdo->prepare($sql2);
$stmt2->execute();
if ($row = $stmt2->fetch()) {
}
else {
}
$pdo->commit();
echo "OK!";
}
catch(Exception $e) {
echo $e->getMessage();
$pdo->rollBack();
}
So in my code I used the same $pdo twice like
$stmt = $pdo->prepare($sql);
$stmt2 = $pdo->prepare($sql2);
and then
$pdo->commit();
When it is just one stmt the code will show the database data fine.
I haven't successfully tested it since there are syntax errors in other files that prevent this from running. I'm very new to PDO, so could anyone tell me if this is fine to run? Thanks!
Example (PDO) using '?'
<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>
Looking to the example you can see your mistakes.
first:
$sql = "SELECT * FROM table1 WHERE table1.id = ?";
second:
$stmt = $pdo->prepare($sql);
for($id=1;$id<3;$id++){
$stmt->execute($id);
$result=$stmt->fetchAll();
}
Sorry for my English but it's not my mother tongue.

PHP PDO mysql_result() equivalent?

What would i use in PDO instead of old mysql_resul()?
function ib_uk_isvalid($db,$uk) {
try {
$sth = $db->prepare("SELECT count(*) FROM ib_userkeys WHERE value=:val");
$sth->bindParam(":val",$uk);
$sth->execute();
$numrows = $sth->fetchColumn();
if($numrows>=1) {
$sth2 = $db->prepare("SELECT * FROM ib_userkeys WHERE value=:val");
$sth2->bindParam(":val",$uk);
$sth2->execute();
$res = $sth2->fetchAll();
print($res[0]->type);
} else {
return 0;
}
} catch (PDOException $e) {
return $e->getMessage();
}
}
ib_uk_isvalid($db,1234)
Gives me error because it returns table instead of an object (which i need).
function ib_uk_isvalid($db, $uk) {
$query = $db->prepare('SELECT * FROM ib_userkeys WHERE value = :val LIMIT 1');
$query->bindValue(':val', $uk);
$query->execute();
$row = $query->fetch(PDO::FETCH_OBJ);
return $row ? $row->type : 0;
}
... is how I'd write that. It may fix the problem.

Categories