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
Related
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.
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();
<?php
class Worker extends Core {
public $name;
public $surname;
public $dob;
public $skills;
public $postcode;
public $street;
public $email;
public $tel;
public $ern;
public $result;
public function __construct () {
$this->name = 'name';
$this->surname = 'surname';
$this->dob = 'dob';
$this->skills = 'skills';
$this->postcode = 'postcode';
$this->street = 'street';
$this->email = 'email';
$this->tel = 'tel';
$this->ern = 'ern';
}
//Saving worker data to database, need provide group name (table name)
public function saveWorker($group) {
if(!(isset($this->conn))) parent::__construct();
try
{
$this->conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //catch exceptions
$q = 'INSERT INTO :group (name, surname, dob, skills, postcode, street, email, tel, erefnumber) VALUES (
:name,
:surname,
:dob,
:skills,
:postcode,
:street,
:email,
:tel,
:erefnumber)'; //sql query with group name
$stmt = $this->conn->prepare($q);
$stmt -> bindValue(':group', $group, PDO::PARAM_STR);
$stmt -> bindValue(':name', $this->name, PDO::PARAM_STR);
$stmt -> bindValue(':surname', $this->surname, PDO::PARAM_STR);
$stmt -> bindValue(':dob', $this->dob, PDO::PARAM_STR);
$stmt -> bindValue(':skills', $this->skills, PDO::PARAM_STR);
$stmt -> bindValue(':postcode', $this->postcode, PDO::PARAM_STR);
$stmt -> bindValue(':street', $this->street, PDO::PARAM_STR);
$stmt -> bindValue(':email', $this->email, PDO::PARAM_STR);
$stmt -> bindValue(':tel', $this->tel, PDO::PARAM_STR);
$stmt -> bindValue(':erefnumber', $this->erefnumber, PDO::PARAM_STR);
$results = $stmt->execute();
if($results > 0)
{
return 'Dodano: '.$ilosc.' rekordow';
}
else
{
return 'Wystapil blad podczas dodawania rekordow!';
}
}
catch(PDOException $e)
{
return 'There was some error: ' . $e->getMessage();
}
unset($stmt);
}
//no exceptions
public function getWorker()
{
$workerData = array (
"name" => $this->name,
"surname" => $this->surname,
"dob" => $this->dob,
"skills" => $this->skills,
"postcode" => $this->postcode,
"street" => $this->street,
"email" => $this->email,
"tel" => $this->tel,
"tel" => $this->erefnumber
);
return $workerData;
} // end getWorker();
public function searchWorker($name, $surname, $dob, $skills, $postcode, $street, $email, $tel, $erefnumber) {
}
function deleteWorker() {
}
function getEmployer() {}
public function __sleep () {
parent::__sleep();
}
} // end Person;
//DB connection
class Core {
public $conn;
public function __construct() {
$this->dbConnect();
}
public function dbConnect() {
$host = 'localhost';
$port = '3307';
$username = 'modium_test';
$password = 'test';
$database ='modium_test';
try{
$this->conn = new PDO('mysql:host='.$host.';dbname='.$database.';port='.$port, $username, $password );
echo 'Connection successful!';
echo var_dump($this->conn);
}
catch(PDOException $e){
echo 'Error: ' . $e->getMessage();
}
}
public function __sleep () {
unset($this->conn);
}
}
}
The query just doesn't work. Every previous function worked, but when I try to INSERT tables via sql query, nothing happends.
Worker is an object it's created well, then i get some POST array assigned to it, wich also works fine then i try to saveWorker but it gives nothing.
The invoking line:
var_dump($worker);
if (isset($worker)) echo 'worker is set';
if (isset($worker->conn)) echo 'thers connection is set';
$worker->saveWorker('workers');
With added lines:
echo "\nPDO::errorInfo():\n";
print_r($stmt->errorInfo());
print_r($this->conn->errorInfo());
echo "end of error info";
It gives me:
PDO::errorInfo():
Array ( [0] => ) Array ( [0] => 00000 )
end of error info
$stmt->execute() returns a boolean value (Manual). Try,
$results = $stmt->execute();
if($results !== FALSE) {
return 'Dodano: '.$ilosc.' rekordow';
} else {
return 'Wystapil blad podczas dodawania rekordow!';
}
Also, you cannot bind tablename.
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;
}
If I am doing an old query to return a row I would do something like this:
$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" LIMIT 1';
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
echo $row['id'];
How do I do that with a Prepared Statement? I can get this far...
$stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? LIMIT 1");
if ($stmt->execute(array($_POST['email']))) {
// what goes in here to pull out this one row?
}
Secondly, if I have multiple rows I would do it like this:
$sql = 'SELECT id FROM table WHERE email="' . mysql_real_escape_string($email) . '" ';
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {
echo $row['id'];
}
Likewise, with PDO I get to a similar place...
$stmt = $dbh->prepare("SELECT id FROM table WHERE email = ? ");
if ($stmt->execute(array($_POST['email']))) {
// what goes in here to loop through the rows??
//
// something like this...?
//
while ($row = $stmt->fetch()) {
echo $row['id'];
}
}
Assuming you're connected to the DB and $dbh is your PDO object.
<?php
$email = 'myEmail#somesite.com';
$stmt = $dbh->prepare("SELECT `id` FROM `table` WHERE `email` = ?");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->bindParam(1, $email, PDO::PARAM_STR);
$stmt->execute();
/* One row. */
$result = $stmt->fetch();
if ($result !== FALSE) {
$stmt->closeCursor();
echo $result['id'];
}
/* Multiple rows. */
$result = $stmt->fetchAll();
if ($result !== FALSE) {
foreach ($result as $row) {
echo $row['id'];
}
}
?>
Here is what I use:
For more info on PDO see: http://php.net/manual/en/book.pdo.php
How to use:
//create connection
$connection = new Connection($settings,true);
$conn = $connection->conn;
//query
$sql = "SELECT StateName as State, StateAbbr as Abb FROM State";
$values = array(":Abbr" => "AL");
$query = new Query($conn);
$testArr = $query->getArrayFromQuery($sql, $values);
CONNECTION: (Connection.php)
class Connection
{
public $conn = null;
/**
* Creates PDO Database Connection
*
* #param array $params Connection Data (host,database,username,password)
* #param bool $useErrorReporting True to Show Errors (optional)
* #sets Database Connection
* #access public
*/
public function __construct($params,$useErrorReporting=false)
{
try
{
$host = "";
$database = "";
$username = "";
$password = "";
if(isset($params) && is_array($params))
{
$host = $params['database_connection']['host'];
$database = $params['database_connection']['database'];
$username = $params['database_connection']['username'];
$password = $params['database_connection']['password'];
$dsn = 'mysql:dbname='.$database.';host='.$host;
$dbh = new PDO($dsn, $username, $password, array(PDO::ATTR_PERSISTENT => true));
//display errors if true
if($useErrorReporting)
{
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
else
{
$dbh = null;
}
}
catch (PDOException $e)
{
throw new Exception('Connection Failed: '.$e->getMessage());
}
$this->conn = $dbh;
}
QUERY: Query.php
Class Query
{
private $conn = null;
/**
* sets query properties
*
* #param object $conn pdo connection object
* #return void
* #access public
*/
public function __construct($conn)
{
$this->conn = $conn;
}
/**
* getArrayFromQuery
* gets array from given query
*
* #param string $sql sql statement
* #param array $values array values to replace (":value" => 2)
* #return array
* #access public
*/
public function getArrayFromQuery($sql, $values)
{
$retValue = array();
$conn = $this->conn;
$statement = "";
try
{
//prepare sql statement
$statement = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
//add values
if(isset($values) && is_array($values))
{
$statement->execute($values);
}
//set return array to result array
$retValue = $statement->fetchAll();
}
catch (PDOException $e)
{
throw new Exception("PDO Query Error: ".$e->getMessage());
}
catch(Exception $e)
{
throw new Exception("Process Query Error: ". $e->getMessage());
}
return $retValue;
}
}