how to get primary key value of newly inserted user in zend - php

i have a problem on my project im currently working on and
this is my register controller
every time a user registers there will be a default image that will be displayed in their profile
public function registerAction()
{
$form = new Application_Form_Users();
$form->submit->setLabel('Register');
$this->view->form = $form ;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$id = $form->getValue('uid');
$firstname = $form->getValue('firstname');
$lastname = $form->getValue('lastname');
$email = $form->getValue('email');
$username = $form->getValue('username');
$password = $form->getValue('password');
$vpassword = $form->getValue('vpassword');
if ($password == $vpassword) {
$register = new Application_Model_DbTable_Users();
$password = md5($password);
$register->addUser($firstname , $lastname , $email , $username , $password );
if ($register) {
$register = new Application_Model_DbTable_Users();
$uid = $form->populate($register->getUser($id));
$addimg = new Application_Model_DbTable_Images();
$imagepath = APPLICATION_PATH.'/../public/upload/';
$addimg->addImage($uid , $imagepath);
}
$this->_helper->redirector('index');
} else {
$this->view->errorMessage = "Passwords don't match.";
}
} else {
$form->populate($formData);
}
}
}
this is my function to add default image path into my database
public function addImage($uid , $imgpath)
{
$data = array(
'uid' => $uid ,
'imgpath' => $imgpath ,
);
$this->insert($data);
}
but i got an error because my uid is null my question is how to get the value of uid in my users table, also users table and images table have a relation.

If you are using Zend_Db_Table then you can do something like this in addUser():
public function addUser($firstname , $lastname , $email , $username , $password ){
$user = $this->createRow();
$user->fname = $firstname;
$user->lname = $lastname;
...
$user->save();
return $user->id;
}
This will return you user id so you can do:
$id = $register->addUser($firstname , $lastname , $email , $username , $password );
and
$addimg->addImage($id , $imagepath); //$id, not $uid !

You can put a default value for $imgpath in your database for each new entry.

You can use the lastInsertId() function within the Zend_Db_Adapter class.
http://framework.zend.com/manual/1.12/en/zend.db.adapter.html#zend.db.adapter.write.lastinsertid
In your case it should be:
$this->getAdapter()->lastInsertId()
after your last line in the addImage method.
Warning: This does not work with all SQL adapters (like PostgreSQL)

From what i can get from your code, you're adding a new user, and then, adding an image related to his id.
$uid = $form->populate($register->getUser($id));
$addimg = new Application_Model_DbTable_Images();
$imagepath = APPLICATION_PATH.'/../public/upload/';
$addimg->addImage($uid , $imagepath);
And, you get an "error" because $uid is null. But $id shouldn't be null, and it should be the ID of the user you just added.
So you might try this and see if it works for you
$addimg->addImage($id , $imagepath);

Related

php data on crud doesn't inserted

im making an insert function on php, everything is ok, there is no error but the data doesnt show up in the database, here is my php file
<?php
include 'koneksi/koneksi.php';
if(isset($_POST['Submit'])) {
$id_koperasi = $_POST['id'];
$nama_koperasi = $_POST['nama'];
$alamat = $_POST['alamat'];
$telp = $_POST['telp'];
$hp = $_POST['hp'];
$nama_cp = $_POST['kontak'];
$email = $_POST['email'];
$nama_cp = $_POST['kontak'];
$tanggal = $_POST['tgl'];
$ket_fu = $_POST['ket'];
$hasil_pembahasan = $_POST['hasil'];
$status = $_POST['stat'];
$query = "INSERT INTO t_koperasi(id,id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status) VALUES ('',
'$id_koperasi',
'$nama_koperasi',
'$alamat',
'$telp',
'$hp',
'$nama_cp',
'$tanggal',
'$ket_fu',
'$hasil_pembahasan',
'$status')"
;
if (mysqli_query($con,$query)) {
header("location:index.php");
}else {
error_log( "This code has errors!" );
}
}
include 'views/v_form.php';
?>
and this is my database t_koperasi structure
The id is auto increasing, so you should remove id column in you insert sql. Also, the method you are using is dangerous, you should not totally trust what pass to you by other users in you website page, instead, you need to add filter functions.
You Query Should Look Like this. At Least in postgresql and MySql
$query = "INSERT INTO t_koperasi(id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status) VALUES (
'".$id_koperasi."',
'".$nama_koperasi."',
'".$alamat."',
'".$telp."',
'".$hp."',
'".$nama_cp."',
'".$tanggal."',
'".$ket_fu."',
'".$hasil_pembahasan."',
'".$status."')"
;
You do not need to insert value into ID .Because ID expected to be the primary key with default value (auto increment).
Hope This works for you!
Simple remove id and ' ' . i hope work fine.
or
You just copy this code and past your project
<?php
include 'koneksi/koneksi.php';
if(isset($_POST['Submit'])) {
$id_koperasi = $_POST['id'];
$nama_koperasi = $_POST['nama'];
$alamat = $_POST['alamat'];
$telp = $_POST['telp'];
$hp = $_POST['hp'];
$nama_cp = $_POST['kontak'];
$email = $_POST['email'];
$nama_cp = $_POST['kontak'];
$tanggal = $_POST['tgl'];
$ket_fu = $_POST['ket'];
$hasil_pembahasan = $_POST['hasil'];
$status = $_POST['stat'];
$query = "INSERT INTO t_koperasi(id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status) VALUES ('$id_koperasi',
'$nama_koperasi',
'$alamat',
'$telp',
'$hp',
'$nama_cp',
'$tanggal',
'$ket_fu',
'$hasil_pembahasan',
'$status')"
;
if (mysqli_query($con,$query)) {
header("location:index.php");
}else {
error_log( "This code has errors!" );
}
} include 'views/v_form.php';

Write to Joomla database

I have a cool component for joomla that help me register users by creating a url (see the link).
joomla extention
What i would like to do is to be able to write on a different table using the same method:
This is the code that help with user registration:
//http://YOURSITE.COM/index.php?option=com_hoicoiapi&task=registration&name=NAME&username=USERNAME&passwd=PASSWORD&email=EMAIL
public function registration()
{
$name = JRequest::getVar('name');
$username = JRequest::getVar('username');
$passwd = JRequest::getString('pass');
$email = JRequest::getVar('email');
$data = array(
"name"=>$name,
"username"=>$username,
"password"=>$passwd,
"password2"=>$passwd,
"email"=>$email,
"block"=>1,
"groups"=>array("2"),
"sendEmail"=>("1"),
);
$user = new JUser;
//Write to database
if(!$user->bind($data)) {
$status = "Could not bind data. Error: " . $user->getError();
}
if (!$user->save()) {
$status = "Could not save user. Error: " . $user->getError();
}
else {
$status = "Success";
}
$message = array(
'message' => $status
);
header('Content-Type: application/json');
echo json_encode ($message);
jexit();
}
To be more explicit, i would like to be able to write comments in a table called belvw_zoo_comment
Is there a way to do that by just modifying the above code? i m thinking of something like this:
//http://YOURSITE.COM/index.php?option=com_hoicoiapi&task=comment&author=AUTHOR&email=EMAIL&content=CONTENT
public function comment()
{
$author = JRequest::getVar('author');
$email = JRequest::getVar('email');
$content = JRequest::getVar('content');
$data = array(
"author"=>$author,
"email"=>$email,
"content"=>$content,
);
$comment = new comment;
//Write to database
if(!$comment->bind($data)) {
$status = "Could not bind data. Error: " . $user->getError();
}
if (!$comment->save()) {
$status = "Could not save user. Error: " . $user->getError();
}
else {
$status = "Success";
}
$message = array(
'message' => $status
);
header('Content-Type: application/json');
echo json_encode ($message);
jexit();
}
Of course the above code is not working.
In the beginning of your code add:
$comment = JRequest::getVar('comment');
Then inside the success clause add the following block
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->insert('#__zoo_comment');
$query->set('name_of_field = '.$db->quote($comment));
$db->setQuery( $query );
$db->execute();
You would have to change the name of 'name_of_field' to the name of your field and it assumes that the comment is in a field called 'comment' in the form submitted.
So you would get:
public function registration()
{
$name = JRequest::getVar('name');
$username = JRequest::getVar('username');
$passwd = JRequest::getString('pass');
$email = JRequest::getVar('email');
$comment = JRequest::getVar('comment');
$data = array(
"name"=>$name,
"username"=>$username,
"password"=>$passwd,
"password2"=>$passwd,
"email"=>$email,
"block"=>1,
"groups"=>array("2"),
"sendEmail"=>("1"),
);
$user = new JUser;
//Write to database
if(!$user->bind($data)) {
$status = "Could not bind data. Error: " . $user->getError();
}
if (!$user->save()) {
$status = "Could not save user. Error: " . $user->getError();
}
else {
$status = "Success";
//Save comment
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->insert('#__zoo_comment');
$query->set('name_of_field = '.$db->quote($comment));
$db->setQuery( $query );
$db->execute();
}
$message = array(
'message' => $status
);
header('Content-Type: application/json');
echo json_encode ($message);
jexit();
}
This is the code that eventually worked for me:
public function event()
{
//$id = JRequest::getVar('id');
$ide = JRequest::getVar('ide');
$name = JRequest::getVar('name');
$email = JRequest::getVar('email');
$confirmed = JRequest::getVar('confirmed');
$quantity = JRequest::getVar('quantity');
$ip = $_SERVER['REMOTE_ADDR'];
$date = date('Y-m-d H:i:s');
//Custom Joomla code for inseting to comment table starts
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Insert columns.
$columns = array('ide', 'name','email','confirmed', 'ip','date'); // table column names
// Insert values.
$values = array($db->quote($ide), $db->quote($name), $db->quote($email), $db->quote($confirmed), $db->quote($ip) , $db->quote($date)); // values
// Prepare the insert query.
$query
->insert($db->quoteName('#__rseventspro_users'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
$message=$db->execute();
$last_id = $db->insertid();
$query1 = $db->getQuery(true);
// Insert columns.
$columns1 = array('ids', 'quantity'); // table column names
// Insert values.
$values1 = array($db->quote($last_id), $db->quote($quantity)); // values
// Prepare the insert query.
$query1
->insert($db->quoteName('#__rseventspro_user_tickets'))
->columns($db->quoteName($columns1))
->values(implode(',', $values1));
// Set the query using our newly populated query object and execute it.
$db->setQuery($query1);
$message=$db->execute();
header('Content-Type: application/json');
echo json_encode ($message);
jexit();
//Custom Joomla code for inseting to comment table starts
}

how to get primary key id of a registered email

i have a problem on my project im currently working on and
this is my Email controller
i want to get the id of an email registered in my database
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$imail = $form->getValue('email');
$users = new Application_Model_DbTable_Users();
$row = $users->fetchRow($users->select('uid')->where('email = ".$imail."'));
/* if ($row == 1) {
$token = uniqid(mt_rand(), true);
$userpass = new Application_Model_DbTable_Password();
$userpass->addToken($uid , $token);
} else { $this->view->errorMessage = "Email not registered"; }
*/
//$this->emailAction();
}
i just need to get the id to be able to shift to my next function but i cant do it also
i think this might be unrelated but i did this on pure php and it works fine
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$getemail = mysql_query("SELECT `uid` FROM `users` WHERE `email` ='$email'");
$resemail = mysql_num_rows($getemail);
if ($resemail == 0) {
echo "Email id is not registered";
}
$token = uniqid(mt_rand(), true);
$getoken = mysql_query("INSERT INTO `password_recovery` (`uid`,`token`) VALUES ((SELECT `uid` FROM `users` WHERE `email` = '$email'),'$token') ");
how can i do this logic in zendframework 1 thank you
Solution of Jehad Keriaki is correct, but unsafe. Use prepared statement syntax instead, for example:
$row = $users->fetchRow($users->select('uid')->where('email = ?', $imail));
It will protect you from SQL injection attack.
Try changing
$row = $users->fetchRow($users->select('uid')->where('email = ".$imail."'));
to
$row = $users->fetchRow($users->select('uid')->where('email = "$imail"'));
I think the issue is with the dots, which you still can use as:
$row = $users->fetchRow($users->select('uid')->where('email = "'.$imail.'"'));

Redbeanphp one to one relation

In my project have 2 entites in my db namely User and Account. One User has one account.User table has account_id field as foreign key to reference Account entity.
I am generating automaticly a new account for user. Everything gets created as I expect.But how can I reference an account for a parcticular user. Here is my registration script
public function register ($data = null)
{
if ($data != null) {
try {
$user = R::dispense('user');
$user->name = $data['name'];
$user->lastname = $data['last-name'];
$user->username = $data['username'];
$user->password = $data['password'];
$user->email = $data['email'];
$user->city = $data['city'];
$user->country = $data['country'];
//create account for user
$account = R::dispense('account');
$account->account_no = $this->genAccountNumber();
$account->money_sum = 0;
$user->account = $account;
$id = R::store($user);
return $id;
} catch (Exception $e) {
echo $e->getMessage;
}
}
}
Would be grateful for any help
You don't need to change anything - your way is correct. The line
$user->account = $account;
is the right way to do it - assuming you are running in fluid mode, your schema will be updated automatically to create the foreign key relationship for you this way.
To access the account, you just need to use $user->account.
echo $user->account;
will show you all the properties of the account bean.
Instead of giving account bean as foreign reference to user bean, just add account_id field as foreign key to user table.
public function register ($data = null){
if ($data != null) {
try {
$user = R::dispense('user');
$user->name = $data['name'];
$user->lastname = $data['last-name'];
$user->username = $data['username'];
$user->password = $data['password'];
$user->email = $data['email'];
$user->city = $data['city'];
$user->country = $data['country'];
//create account for user
$account = R::dispense('account');
$account->account_no = $this->genAccountNumber();
$account->money_sum = 0;
$account_id = R::store($account);
$user->account_id = $account_id; // this is the line you have to change
$id = R::store($user);
return $id;
} catch (Exception $e) {
echo $e->getMessage;
}
}}
And when loading a bean you can directly access account instance from user bean
(constraint being if there is a one-to-one or one-to-many maaping)
$account = $user->account;

Codeigniter Updating Edit Page

I have created an edit page which repopulates their information into the correct fields (based on the ID) and they can amend the details...
What I want now is for the Submit button to update this information in the database table?
This is the Edit Section in my Controller:
function edit($id = 0){
$this->load->model('blogmodel');
if( $this->input->post() ){ #if form submitted
$data = array();
$id = $this->input->post('id'); #to be used in the where clause for updation
$data['name'] = $this->input->post('name');
$data['address'] = $this->input->post('address');
$data['sEmail'] = $this->input->post('sEmail');
$this->blogmodel->update_blog($data,$id);
}else{
// Form Validation required
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('sEmail', 'Sender Email', 'required|valid_email');
$this->form_validation->set_message('required', '%s is required');
$this->form_validation->set_error_delimiters('<span class="error">', '</span><br />');
$sql = 'SELECT * FROM databse.blogs WHERE id = ?';
echo $sql . ' - '. $id;
$sql_params = array($id);
$query = $this->db->query($sql, $sql_params);
$form = $query->row_array();
//$date['form'] = $form;
$data['inputs'] = array('name' => $form['name'],
'address' => $form['address'],
'semail' => $form['email'],
'nickname' => $form
);
$data['Name']= $form['name'];
$data['Address']= $form['address'];
$data['Email']= $form['email'];
$this->load->view('blog_content',$data);
$data = $this->input->post();
$result = $this->blogmodel->update_blog($data,$id);
$this->load->view('blog_success');
}
}
}
So Far this is my Model:
function send_blog(&$data){
$data['name'] = $this->input->post('name');
$data['address'] = $this->input->post('address');
$data['sEmail'] = $this->input->post('sEmail');
$sql = "UPDATE database.blogs (name, address, email) WHERE id = $id
VALUES (".$this->db->escape($data['name']).",
".$this->db->escape($data['address']).",
'".$data['sEmail']."');";
$this->db->query($sql);
}
function update(&$data,$id){
$data['name'] = $this->input->post('name');
$data['address'] = $this->input->post('address');
$data['sEmail'] = $this->input->post('sEmail');
$this->db->where('id', $this->input->post('id'));
$this->db->update('blog', $data);
}
}
What is the current_url() here? I'm guessing it to be function edit(). In your function edit just do the below changes:
function edit($id = 0){
if( $this->input->post() ){ #if form submitted
$data = array();
$id = $this->input->post('id'); #to be used in the where clause for updation
/*
Retrieve all the post variables in the $data and send to model for updation
*/
$this->your_model->update_function( $data, $id );
redirect('controller/edit/'.$id, 'refresh'); #redirect to the same function to show the form or success page
}else{
/*
Your rest of the function as it is
*/
}
}
Update
Your controller changes:
function edit($id = 0){
if( $this->input->post() ){ #if form submitted
$data = array();
$id = $this->input->post('id'); #to be used in the where clause for updation
$data['name'] = $this->input->post('name');
$data['address'] = $this->input->post('address');
$data['sEmail'] = $this->input->post('sEmail');
$data['nickname'] = $this->input->post('nickname');
$data['blogregion'] = $this->input->post('blogregion');
$data['startdate'] = $this->input->post('startdate');
$data['blogtitle'] = $this->input->post('blogtitle');
$data['timesperweek'] = $this->input->post('timesperweek');
$data['profiletext'] = $this->input->post('profiletext');
$data['abouttext'] = $this->input->post('abouttext');
$data['status'] = 0;
$data['userid'] = $id;
$this->newblogsetupmodel->update_blogforus( $data, $id );
redirect('newblogsetup/edit/'.$id, 'refresh'); #redirect to the same function to show the form or success page
}else{
#rest of the controller here
}
}
Your model changes:
function update_blogforus($data, $id){
echo "<pre>";print_r( $data );die; #to print the data received from controller, see if its coming okay or make correction in the controller for the same
/*$data['name'] = $data['name'];
$data['address'] = $data['address'];
$data['sEmail'] = $data['sEmail'];
$data['nickname'] = $data['nickname'];
$data['blogregion'] = $data['blogregion'];
$data['startdate'] = $data['startdate'];
$data['blogtitle'] = $data['blogtitle'];
$data['timesperweek'] = $data['timesperweek'];
$data['profiletext'] = $data['profiletext'];
$data['abouttext'] = $data['abouttext'];
$data['status'] = 0;
//$data['userid'] = $data['user']->id;
*/
$this->db->where('id', $id);
$this->db->update('newblogsetup', $data);
echo $this->db->last_qeury();die; #to see the query being executed, run it in your phpMyadmin and see if its updating as required.
}
New Changes
Controller:
$data['id'] = $id; #save the data in an element to echo in the hidden field of the form
$this->load->view('newblogsetup_sent', $data); #load the data to the page
In your edit page change this line
<?php echo form_hidden('id');?>
To:
<?php echo form_hidden( 'id', $id );?>

Categories