PDO JSON encode multiple HTML table rows - php

I am building a PHP function that is supposed to answer a jQuery Ajax call, depending on what id is submitted. There can be multiple forms with the same ID and I can't figure out why it is not sending back more than one record. PS: My dad will kill me if I don't figure this out by Monday...
My PHP:
<?php
if (!empty($_GET['id'])) {
$id = $_GET['id'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=blankett', 'root', 'root');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `forms`
WHERE `id` = '$id'";
$statement = $objDb->prepare($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array();
foreach ($list as $row ) {
$out[] = '<tr><td>'.$row['name_form'].'</td> <td>'.$row['date_added'].'</td></tr>';
}
echo json_encode(array('error' => false, 'list' => $out));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
?>

You're using the prepared statement incorrectly. First, you should not be putting your variable in the statement. Second, you need to execute the statement.
Here is an example from the php.net site:
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
And here is how you would do it:
$sql = "SELECT *
FROM `forms`
WHERE `id` = :formID";
$statement = $objDb->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$statement ->execute(array(':formID' => $id));
$list= $statement ->fetchAll();

Related

Mysql - Get Last inserted ID is not working

I dont know why this is not working. The LAST_INSERT_ID() is not being catched, can someone help me please?
$query = "
INSERT INTO products_categories (
name,
url
) VALUES (
:name,
:url
) SELECT LAST_INSERT_ID();
";
$query_params = array(
':name' => $_POST['name'],
':url' => $_POST['url']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo 0;
return true;
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$id_category = $result["id"];
"You can remove your SELECT LAST_INSERT_ID() part from the query and use $db->lastInsertId(); instead." - #barell
Try this;
<?php
$query = "
INSERT INTO products_categories (
name,
url
) VALUES (
:name,
:url
)
";
$query_params = array(
':name' => $_POST['name'],
':url' => $_POST['url']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
echo 0;
return true;
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//$id_category = $result["id"];
$id_category = $db->lastInsertId();
Hope it helps

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.

prepare statement in php not work

Hi i get a value with post methos and i want to check it with function func_check_seven_userid()
when i use :
$stmt = $this->conn->prepare("SELECT * FROM content where content_id= ".$this->seven);
$stmt->execute();
it work.
but when i use :
$stmt = $this->conn->prepare("SELECT * FROM content WHERE content_id = :id");
$stmt->execute(array(":id" => $this->seven));
it is not work!!!
my complet code is :
<?php
class insert_content {
private $conn;
private $seven;
private $row_id;
//**********************************************************************
function connect() {
include 'db_connection.php';
try {
$this->conn = new PDO("mysql:host=$servername;dbname=$db_name", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo "Connection failed: " . $e->getMessage();
}
}
//************************************************************************
private function func_check_seven_userid() {
$stmt = $this->conn->prepare("SELECT * FROM content WHERE content_id = :id");
$stmt->execute(array(":id" => $this->seven));
$row = $stmt->fetch();
$this->row_id = $row[0];
if ($this->row_id) {
echo 'yes';
}
else {
echo 'no';
}
}
//****************************************************************
function __construct($parms) {
$this->connect();
$this->seven = $parms['seven'];
$this->func_check_seven_userid();
}
function __destruct() {
$this->conn = null;
}
}
if (isset($_POST['seven'])) {
$parms = array('seven' => ($_POST['seven']));
$class = new insert_content($parms);
}
?>
thanks for help
I found this:
<?php
/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>
on http://php.net/manual/en/pdo.prepare.php
Here the statement is prepared with PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY
Maybe it does the difference. Hope it helps

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

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);

PHP PDO put commands in transaction problem

I am using PHP PDO for work with database SQLITE3. Can somebody show me how to put this commands in one transaction ?
$db = new PDO('sqlite:/var/db/fan_coil.db');
$sql = 'DELETE FROM fan_coil_plan WHERE fan_coil_id = :fan_coil_id;';
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':fan_coil_id' => $fan_coil_id));
$sql = ' DELETE FROM fan_coil_working_mode WHERE fan_coil_id = :fan_coil_id;';
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':fan_coil_id' => $fan_coil_id));
//****************** inserting working mode *************************************************************************************************
$i = 0;
$sql = 'INSERT INTO fan_coil_working_mode
(fan_coil_id,working_mode, temperature_set_point, max_positive_temperature,min_positive_temperature,mode_type,max_fan_speed)
VALUES(:fan_coil_id,:working_mode,:temperature_set_point,:max_positive_temperature,:min_positive_temperature,:mode_type,:max_fan_speed)';
$sth = $db->prepare($sql);
foreach ($modes as $key => $value) {
//file_put_contents('error.txt',$value['temperature_set_point'], FILE_APPEND );
$working_mode = '0'; //treba da se izbaci ova kolona iz tabele
$temperature_set_point = $value['temperature_set_point'];
$max_positive_variation = $value['max_positive_variation'];
$min_positive_variation = $value['min_positive_variation'];
$max_fan_speed = $value['max_fan_speed'];
$mode_type = ++$i;
$sth->execute(array(':fan_coil_id' => $fan_coil_id, ':working_mode' => $working_mode, ':temperature_set_point' => $temperature_set_point, ':max_positive_temperature' => $max_positive_temperature, ':min_positive_temperature' => $min_positive_temperature, ':mode_type' => $mode_type, ':max_fan_speed' => $max_fan_speeed));
}
$db = new PDO('sqlite:/var/db/fan_coil.db');
$db->beginTransaction();
try {
// your code
$db->commit();
}catch(PDOException $e) {
$db->rollBack();
throw $e;
}

Categories