I have a form that has a hidden field (the date). I want this data to be inserted with the note that is submitted as well. I only have 3 columns in my table. ID,Note_id and Note.
So if a user submits a note the insert statement should add the date infront of the note.
My Current SQL Statement:
$pdoOptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
$pdo = new PDO("mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, MYSQL_USER,MYSQL_PASSWORD,$pdoOptions);
$data = [
'notes' => $_POST['notes'],
'id' => $_POST['rowID'],
'date2' => $_POST['date'],
];
$sql = "INSERT INTO notes (note_id, note) Values(:id, :notes)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
My thought was I could add the :date2 to this but it does not seem to work
$pdoOptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
$pdo = new PDO("mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, MYSQL_USER,MYSQL_PASSWORD,$pdoOptions);
$data = [
'notes' => $_POST['notes'],
'id' => $_POST['rowID'],
'date2' => $_POST['date'],
];
$sql = "INSERT INTO notes (note_id, note) Values(:id, :date '-' :notes)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
Whats the best method of doing this? I know I can have another column but I dont want that structure. The way it is displayed on the users side needs to be like this.
Thank you
Use CONCAT()
$sql = "INSERT INTO notes (note_id, note) Values(:id, CONCAT(:date,'-',:notes))";
This will work
Related
I have this SQL Query
$sql = $conn->prepare('INSERT INTO Accounts (Status, Username, Password, FirstName, LastName, EmailAddress, API_Status, API_Key, About) VALUES (:Status, :Username, :Password, :FirstName, :LastName, :EmailAddress, :API_Status, API_Key, :About)');
$sql->execute(array('Status' => 'NotActive', 'Username' => $Username, 'Password' => $PasswordHash, 'FirstName' => $FirstName, 'LastName' => $LastName, 'EmailAddress' => $EmailAddress, 'API_Status' => 'OFF', 'API_Key' => $API_Key, 'About' => $Other));
When executing this query I'm using try { and
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
Now when I run script Iget this PHP error:
Catchable fatal error: Object of class PDOStatement could not be
converted to string in /var/www/html/register.php on line 94
How I can slove this problem?
Problems with question.
Wrong naming. SQL is a text that is passed to prepare(). While returned value is an object. Problem not solved.
Due to wrong naming the OP is trying to echo an object. Problem not solved.
Thanks to the great site of Stack Overflow, the OP is taught terrible wrong way of handling PDO errors, with useless try..catch stuff. Problem not solved.
: is missed for one placeholder. The only problem solved.
As a result, next time this query throws an exception, THE SAME UTTERLY USELESS and irrelevant error message will be produced.
What should be done instead?
$sql = 'INSERT INTO Accounts
(Status, Username, Password, FirstName, LastName, EmailAddress,
API_Status, API_Key, About)
VALUES (:Status, :Username, :Password, :FirstName,
:LastName, :EmailAddress, :API_Status, :API_Key, :About)';
$data = array(
'Status' => 'NotActive',
'Username' => $Username,
'Password' => $PasswordHash,
'FirstName' => $FirstName,
'LastName' => $LastName,
'EmailAddress' => $EmailAddress,
'API_Status' => 'OFF',
'API_Key' => $API_Key,
'About' => $Other
);
$conn->prepare($sql)->execute($data);
What do we have here?
proper naming. if one have a fancy of echoing an SQL query, they will be no mistaken.
readability. No long and windy code off the screen, allowing us to visually inspect the query and find the syntax error.
corrected placeholder syntax.
no statement object is echoed. Neither SQL is, as it makes very little sense in case of a prepared statement.
no stupid try..catch block. Means PHP will be able to notify PHP user in case of error occurred.
you can't echo your sql as you are using, you may need to use debugDumpParams() try something like this.
$sql = $conn->prepare('INSERT INTO Accounts (Status, Username, Password, FirstName, LastName, EmailAddress, API_Status, API_Key, About) VALUES (:Status, :Username, :Password, :FirstName, :LastName, :EmailAddress, :API_Status, API_Key, :About)');
$sql->execute(array(':Status' => 'NotActive', ':Username' => $Username, ':Password' => $PasswordHash, ':FirstName' => $FirstName, ':LastName' => $LastName, ':EmailAddress' => $EmailAddress, ':API_Status' => 'OFF', ':API_Key' => $API_Key, ':About' => $Other));
echo $sql->debugDumpParams();
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.
I can't find my mistake, I'm getting Execute fail error
$db = new PDO('mysql:host=localhost; dbname=xxxxxx', 'yyyyyy', 'zzzzzz', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")) or die ("fail");;
$query = "INSERT INTO multiTicker (mtgox,btcstamp,btce,btcchina,myDateTime) VALUES (:mtgox,:btcstamp,:btce,:btcchina,:myDateTime)";
$st = $db->prepare($query) or die ("Query fail");
$st->execute(array(':mtgox' => $mtgox,
':btcstamp' => $btcstamp,
':btce' => $btce,
':btcchina' => $btcchina,
':myDateTime' => $myDateTime)) or die ("Execute fail");
Looks like your DSN is incorrect (you have a space in it). Try this PDO constructor and stop using or die()!
$db = new PDO('mysql:host=localhost;dbname=xxxxxx;charset=utf8', 'yyyyyy', 'zzzzzz', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));
$query = "INSERT INTO multiTicker (mtgox,btcstamp,btce,btcchina,myDateTime) VALUES (:mtgox,:btcstamp,:btce,:btcchina,:myDateTime)";
$st = $db->prepare($query);
$st->execute(array(
':mtgox' => $mtgox,
':btcstamp' => $btcstamp,
':btce' => $btce,
':btcchina' => $btcchina,
':myDateTime' => $myDateTime
));
You don't have to set the default fetch mode to PDO::FETCH_ASSOC but I find it's handy.
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.
Is something wrong with my query
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, ##ServerAdmin## and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
$sql = $db->query(
"INSERT INTO users (user_id, title, first_name, last_name, user_identity_id, email_id, password, office_phone_number, public_id, session_id, address_id, created_by, last_modified_by, created_on, last_modified_on, is_activated, is_deprecated, middle_name, cell_phone_number, superviser_name, superviser_email, superviser_phone_number)
VALUES( :p_user_id,:p_title,:p_first_name,:p_last_name,:p_user_identity_id,:p_email_id,:p_password,:p_office_phone_number,:p_public_id,:p_session_id,:p_address_id,:p_created_by,:p_last_modified_by,:p_created_on,:p_last_modified_on,:p_is_activated,:p_is_deprecated,:p_middle_name,:p_cell_phone_number,:p_superviser_name,:p_superviser_email,:p_superviser_phone_number)",
array(
'p_user_id' => '',
'p_title' => $title,
'p_first_name' => $first_name,
'p_last_name' => $last_name,
'p_user_identity_id' => '',
'p_email_id' => $email,
'p_password' => $pass,
'p_office_phone_number' => $office_ph_no,
'p_public_id' => '',
'p_session_id' => '',
'p_address_id' => '',
'p_created_by' => '',
'p_last_modified_by' => '',
'p_created_on' => '',
'p_last_modified_on' => '',
'p_is_activated' => '',
'p_is_deprecated' => '',
'p_middle_name' => $middle_name,
'p_cell_phone_number' => $cell_ph_no,
'p_superviser_name' => $supervisor_name,
'p_superviser_email' => $supervisor_email,
'p_superviser_phone_number' => $supervisor_ph_no
)
);
$db->commit();
This looks like you're trying to execute a PDO statement using named parameters in Zend.
First thing to check, I assume you've started a transaction?
Also, in my experience named parameters are the same in the query as in the params array, e.g. :param1 is $params = array(':param1'=>'data');
I use the same method as described in the ZF docs "executing a statement using named parameters":
$select = 'select col1,col2 from my_table where con1=:param1 and con2=:param2';
$params = array(
':param1'=> 'somedata',
':param2'=> 'someotherdata'
);
$statement = new Zend_Db_Statement_Pdo($db,$sql);
if($statement->execute($params)){
//ok!
}