Building a response array after binding parameters for PDO - php

I am trying to build the array that will return to my ajax success. How do I build the array after binding it to something like :some variable.
The following script runs to completion, and inserts with no problem into sql. But the variables comment and transaction come back as null in the response. I think the problem is using $comment and $transaction when building the array. What is the right way to reference these values in the array?
require('../dbcon2.php');
//Connection 1
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("UPDATE listings SET comment = :comment, transaction = :transaction, ad_link = :ad_link WHERE id = :id");
// Bind
$stmt->bindParam(':id', $_POST['id']);
$stmt->bindParam(':comment', $_POST['comment']);
$stmt->bindParam(':transaction', $_POST['transaction']);
$stmt->execute();
// Build array
$response = array
('state' => 200, "success" => true, "id" => ':id', "comment" => $comment, "transaction" => $transaction
);
exit(json_encode($response));
}
catch (Exception $e) {
// create a asociative array
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
// encode data and exit.
exit(json_encode($data));
}

As per OP's wish:
Do as you did for "id" => ':id'
"id" => ':id', "comment" => ':comment', "transaction" => ':transaction'
Plus, quoting Jeroen (kudos to)
Why don't you use the $_POST variable? That contains the values you need and you use them already in your database query.

You can't retrieve bound values after calling ->bindParam(); also, the variables $comment and $transaction aren't defined (unless you set them yourself or when using voodoo php settings).
That said, you already know those values:
$response = array(
'state' => 200,
"success" => true,
"id" => $_POST['id'],
"comment" => $_POST['comment'],
"transaction" => $_POST['transaction'],
);
Btw, in the exception branch you have a small bug:
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
^
You should use $e->getMessage() instead.

Related

Why can't I use execute() for an array?

I'm trying to implement a verification email process to my website but I got an error
Fatal error: Uncaught Error: Call to a member function execute() on
bool in :56 Stack trace: #0 {main} thrown in on line 56
Here is my code:
$user_activation_code = md5(rand());
// Nuevo Usuario
$hashed = password_hash($password,PASSWORD_DEFAULT);
$insert_query = 'INSERT INTO clientes (full_name,email,user_activation_code,user_email_status,password,permissions,street,numero,interior,city,state,zip_code,country) VALUES ("$name","$email","$user_activation_code",:user_email_status,"$hashed",cliente,"$street","$numero","$interior","$city","$state","$zip_code",Mexico)';
$statement = $db->prepare($insert_query);
$statement -> execute(
array(
'full_name' => $_POST['name'],
'email' => $_POST['email'],
'password' => $hashed,
'user_activation_code' => $user_activation_code,
':user_email_status' => 'no verificado'
)
);
$result = $statement->fetchAll();
You need to properly bind your array to the query.
PDO for using an associative array you need to have the values in both the query string and the same values in your key.
$insert_query = 'INSERT INTO clientes (full_name,email,user_activation_code,user_email_status,password,permissions,street,numero,interior,city,state,zip_code,country) VALUES (:full_name,:email,:user_activation_code,:user_email_status,:password,"cliente","$street","$numero","$interior","$city","$state","$zip_code","Mexico")';
array(
':full_name' => $_POST['name'],
':email' => $_POST['email'],
':password' => $hashed,
':user_activation_code' => $user_activation_code,
':user_email_status' => 'no verificado'
)
Please also bind your other values such as: $city, $state etc.

PDO Insert SQL not executing with no errors

I am running this code:
$stmt = $pdo_conn->prepare("INSERT into ticket_updates (ticketnumber, notes, datetime, contact_name, contact_email, customer, internal_message, type) values (:ticketnumber, :notes, :datetime, :contact_name, :contact_email, :customer, :internal_message, :type) ");
$stmt->execute(array(':ticketnumber' => $ticketnumber,
':notes' => $TicketSummary,
':datetime' => date("Y-m-d H:i:s"),
':contact_name' => $Ticket_ContactName,
':contact_email' => $Ticket_ContactEmail,
':customer' => 'Y',
':internal_message' => 'N',
':type' => 'update'));
all the table columns exist and are correct but its not getting past this point
i tried a var_dump($stmt); but get nothing
Use the following to verify the connection is established correctly
try
{
$dbh = new PDO("mysql:host=xxxxxxxxxxxx;dbname=streaming", "xxxx", "xxxx");
}
catch (Exception $e)
{
throw new Exception( 'Something really gone wrong', 0, $e);
}
You can also output errors when you execute like so
$sth->execute() or die(print_r($sth->errorInfo(), true));
Finally you may also need to enable errors on the page, so place this in the header of your page or at the very top if it is a single page:
error_reporting(-1);
The minus 1 means that it will print all errors.
Until you have discovered the error it is very hard to diagnose the issue further, but the issue likely falls down to either the connection to the database or how you have formed the parameter array.
Add error reporting to your pdo:
$pdo_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
before executing the insert command.
Then on the insert command, output your errors
$stmt->execute(array(':ticketnumber' => $ticketnumber,
':notes' => $TicketSummary,
':datetime' => date("Y-m-d H:i:s"),
':contact_name' => $Ticket_ContactName,
':contact_email' => $Ticket_ContactEmail,
':customer' => 'Y',
':internal_message' => 'N',
':type' => 'update')) or die("ERROR: " . implode(":", $pdo_conn->errorInfo()))
This should give you an indication of what is wrong and why things are not executing as expected.

Need help transforming Zend Db Select from zf1 to zf2

I am doing a update on my framework. Previously i am using zf1 zend db select for my data access object class. Now, i would like to make a shift and upgrade to zf2. I have problems translating for the insert, update, select, and delete queries and wonder if someone can shed some light to assist me.
What are the new classes that i should use?
Does it involve alot of re-coding?
Any references will helps alot ( Been looking through stackoverflow, but haven found a comprehensive guide)
Below is my code for insert/update/delete/select for zf1
Insert
$userdata = array('email' => $email,
'name' => $name,
'gender' => $gender,
'location' => $location,
'fbid' => $fbid,
'ipaddress' => $ipaddress,
'jointimestamp'=>new Zend_Db_Expr('NOW()'));
$this->dbo->insert('users', $userdata);
return $this->dbo->lastInsertId();
Select
if($this->dbo->fetchOne('SELECT id FROM users WHERE username = ?',$username)){
return true;
}else{
return false;
}
Update
$userdata = array($field => $value);
$this->dbo->update('user', $userdata, $this->dbo->quoteInto('useremail = ?', $this->user));
Also, does zf2 has fetchall, fetchone, fetchrow methods etc?
Appreciate any advices.
After reading the documentation, i have come out with the insert/select/update queries for zf2. Below is the code snippet for benefit of those who may need it in future. I am using Zend\Db\Select as a standalone classes for my custom mvc framework.
Adapter
$adapter = new Zend\Db\Adapter\Adapter(array(
'driver' => 'pdo_mysql',
'host' => DB_HOST,
'database' => DB_PREFIX.DB_NAME,
'username' => DB_USER,
'password' => DB_PW
));
Select
$select = $this->sql->select()
->from('table')
->join('users', 'users.id = table.userid')
->order("table.createdtimestamp DESC");
$statement = $this->sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($result);
return $resultSet->toArray();
Insert
$insert = $this->sql->insert()
->into("messages");
$userdata = array(
'message' => $message,
'createdtimestamp'=>new Zend\Db\Sql\Expression('NOW()'),
'userid' => $userid);
$insert->values($userdata );
$statement = $this->sql->prepareStatementForSqlObject($insert);
$result = $statement->execute();
//return last insert id
return $this->dbo->getDriver()->getLastGeneratedValue();
Update
$update = $this->sql->update()
->table('posts')
->where(array('pid'=>$pid));
$numbercountarr = array('numbercount' => new Zend\Db\Sql\Expression('numbercount+ 1'));
$update->set($numbercountarr );
$statement = $this->sql->prepareStatementForSqlObject($update);
result = $statement->execute();
To count rows
$statement = $this->sql->prepareStatementForSqlObject($query);
$result = $statement->execute();
return $result->count();
Hope this can help those who need it save some time.

PDO Method some issue with my code

Hi i am using a PDO wrap object
https://github.com/Xeoncross/DByte/blob/master/example.php
having some issue with Updates features.
This is their defined function for update
static function update($table, $data, $value, $column)
{
$keys = implode('`=?,`', array_keys($data));
if($statement = DB::query(
"UPDATE`$table`SET`$keys`=? WHERE`$column`=?",
array_values($data + array($value))
))
return $statement->rowCount();
}
My function to update
public function update_users($user_id, $user_name, $user_email, $user_role, $user_phone){
$user_data = array(
'user_name' => $user_name,
'user_email' => $user_email,
'user_pass' => $user_pass,
'user_role' => $user_role,
'user_phone' => $user_phone,
);
$result = DB::update('users', $user_data, $user_id);
}
This is not working Error i am getting is,
Warning: Missing argument 4 for DB::update(), called in \XXXClass.php on line 47 and defined in XXXX\Application\inc\DB.php on line 120
You need to pass in the column name (4th argument of the method):
$result = DB::update('users', $user_data, $user_id, 'user_id'); // I presume `user_id` is the name of that column
Also it doesnt hurt to place spaces between SQL keywords and column/table names:
"UPDATE `$table` SET `$keys`=? WHERE `$column`=?"

NuSoap equivalent of SoapVar()

I don't know much about NuSoap, but unfortunately I have to use it.
I'm trying to follow example code for the dotmailer web service api Here. I need to be able to add custom fields for subscribers.
In the example code custom/additional fields are defined like so;
new SoapVar($FirstName,XSD_STRING,"string","http://www.w3.org/2001/XMLSchema");
Heres the code I have right now;
<?php
function subscribeUserEmail($email)
{
$username = "********";
$password = "********";
$postURL = "http://apiconnector.com/api.asmx?WSDL";
$contact = array (
"Email" => $email,
"AudienceType" => "B2C",
"OptInType" => "Single",
"EmailType" => "Html",
"ID" => -1,
"DataFields" => array(
"Keys" => array("TEST"),
"Values" => array("Name")
)
);
$params = array(
"username" => $username,
"password" => $password,
"contact" => $contact,
"addressbookId" => "******"
);
$client = new soapclient($postURL, true);
$error = $client->getError();
$result = $client->call('AddContactToAddressBook', $params);
echo "<h2>Request</h2>";
print("<pre>".$client->request."</pre>");
echo "<h2>Response</h2>";
print("<pre>".$client->response."</pre>");
echo "<h2>Debug</h2>";
print("<pre>".$client->debug_str."</pre>");
}
?>
If the $contact array is changed to this;
$contact = array (
"Email" => $email,
"AudienceType" => "B2C",
"OptInType" => "Single",
"EmailType" => "Html",
"ID" => -1,
"DataFields" => array(
"Keys" => array("TEST"),
"Values" => array(new SoapVar("Name",XSD_STRING,"string","http://www.w3.org/2001/XMLSchema") )
)
);
And used with a regular soap client, the code works. So I'm pretty sure there aren't any other problems with my function.
I've tried using the following;
new soapval("string", XSD_STRING, "Name","http://www.w3.org/2001/XMLSchema");
As an alternative to the SoapVar() method, but I get the same errors as if I entered the value as plain text.
How can I replicate the functionality of SoapVar() in NuSoap? This appears to be the only issue.

Categories