Write to Joomla database - php

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
}

Related

prepare($sql)->execute() works, but $statement->execute() not

If I use the following statement, my code is working well:
$statement = $this->pdo->prepare($sql)->execute();
But if I use the following statements, my code doesn't work:
$statement = $this->pdo->prepare($sql);
$statement->execute();
Does anyone have an idea, what I'm doing wrong or why this is so?
Here my complete code:
public function deleteUser($pid_user){
/* DESCRIPTION
* delete an user an all his data
*
* PARAMETERS
*
* EXAMPLE
* deleteUser();
*/
try {
//begin transaction
$this->pdo->beginTransaction();
//define all tables to delete all entries from the overgiven user id
//name = name of the table
//column = column to identify the users entries
$tables = array();
$tables[0]["name"] = "snsho_bittrex_apikey";
$tables[0]["column"] = "fk_user";
$tables[1]["name"] = "snsho_bittrex_balances";
$tables[1]["column"] = "fk_user";
$tables[2]["name"] = "snsho_bittrex_deposit_history";
$tables[2]["column"] = "fk_user";
$tables[3]["name"] = "snsho_bittrex_order_history";
$tables[3]["column"] = "fk_user";
$tables[4]["name"] = "snsho_bittrex_withdrawal_history";
$tables[4]["column"] = "fk_user";
$tables[5]["name"] = "snsho_user_settings";
$tables[5]["column"] = "fk_user";
$tables[6]["name"] = "snsho_user";
$tables[6]["column"] = "pid_user";
//do the queries
$sql = '';
foreach($tables as $key => $table){
$sql .= 'DELETE FROM ' . $table["name"] . ' WHERE ' . $table["column"] . ' = ' . $pid_user . ';';
}
//$statement = $this->pdo->prepare($sql)->execute();
$statement = $this->pdo->prepare($sql);
$statement->execute();
if($this->pdo->commit()){
echo "commited";
}else{
echo "commit failed";
}
return TRUE;
} catch (Exception $e) {
$this->adminMessages->setSingleError("Failed: " . $e->getMessage());
$this->pdo->rollBack();
return FALSE;
}
}
Try the execute without the assignment.
$this->pdo->prepare($sql)->execute();
This only returns a true or false.

How does one pass the properties of a $_POST to a Function?

I would like to pass the properties to a function to Update details in a database. I want all the columns that were selected in the form to be passed to a function. Frankly, I don't know what to do.
My code is the following:
if (isset($_POST["updateWineButton"])) {
$wineID = $_POST["wineID"];
$wineCountryID = $_POST["wineCountryID"];
$wineSizeID = $_POST["wineSizeID"];
$wineRatingID = $_POST["wineRatingID"];
$wineColourID = $_POST["wineColourID"];
$packageID = $_POST["packageID"];
$wineCategoryID = $_POST["wineCategoryID"];
$wineCode = $_POST["wineCode"];
$price = $_POST["price"];
$description = $_POST["description"];
$wineRating = $_POST["wineRating"];
$wineIMG = $_POST["wineIMG"];
updateWine($updateWine);
$status = "$description has been updated.";
}
Update Wine Function
function updateWine($wineUpdate)
{
global $pdo;
$statement = $pdo->prepare("UPDATE WINE SET wineID=?, wineCountryID=?, wineSizeID=?, wineRatingID, wineColourID=?,
packageID=?, wineCategoryID=?, wineCode=?, price=?, description=?, wineRating=?, wineIMG=?
WHERE wineID=?");
$statement->execute([$wineUpdate->wineID,
$wineUpdate->wineCountryID,
$wineUpdate->wineSizeID,
$wineUpdate->wineRatingID,
$wineUpdate->wineColourID,
$wineUpdate->packageID,
$wineUpdate->wineCategoryID,
$wineUpdate->wineCode,
$wineUpdate->price,
$wineUpdate->description,
$wineUpdate->wineRatingID,
$wineUpdate->wineIMG]);
$statement->fetch();
}
Something like the following should work for you:
function updateWine()
{
global $pdo;
$keys = [
"wineID", "wineCountryID", "wineSizeID", "wineRatingID", "wineColourID", "packageID", "wineCategoryID",
"wineCode", "price", "description", "wineRating", "wineIMG",
];
$results = [];
foreach ($keys as $index) {
if (isset($_POST[$index])) {
$results[$index] = $_POST[$index];
}
}
$statement = $pdo->prepare("UPDATE WINE SET " . implode('=?, ', array_keys($results)) . "=? WHERE wineID =?");
$statement->execute(array_merge(array_values($results), [$_POST['wineID']]));
$statement->fetch();
}
if (isset($_POST["updateWineButton"]) && isset($_POST['wineID'])) {
updateWine();
}
Hope this helps!
if I understand correctly you want to do something like this,
if (isset($_POST["updateWineButton"])) {
$result = updateWine($_POST);
if($result){
$status = "$description has been updated.";
}else{
$status = "An error occurred.";
}
}
//your function woud then look like ...
function updateWine($postdata){
$wineID = $postdata["wineID"];
$wineCountryID = $postdata["wineCountryID"];
$wineSizeID = $postdata["wineSizeID"];
$wineRatingID = $postdata["wineRatingID"];
$wineColourID = $postdata["wineColourID"];
$packageID = $postdata["packageID"];
$wineCategoryID = $postdata["wineCategoryID"];
$wineCode = $postdata["wineCode"];
$price = $postdata["price"];
$description = $postdata["description"];
$wineRating = $postdata["wineRating"];
$wineIMG = $postdata["wineIMG"];
//udpate your database with the above values
//check if update is successful
return true;
//else if there was an error
return false;
}

MySQL cannot update the rows in the database

I am trying to update my selected row of data but i could not update it. Once i run the code I am getting this output {"RowCount": 0 ,"results": []}. Supposed i should get 1 but i am not getting it. Can i know how to solve this problem.
This is my PHP code:
case 'updateStudent':
$studentUpdateSQL = "UPDATE srs_student SET surname=:surname, forename=:forename,
email=:email WHERE studentid=:id";
$rs = new JSONRecordSet();
$retval = $rs->getRecordSet($studentUpdateSQL, 'ResultSet',
array(':surname'=>$surname,
':forename'=>$forename,
':email'=>$email,
':id'=>$id
));
echo $retval;
break;
This is the JSONRecordSet class:
function getRecordSet($sql, $elementName = "ResultSet", $params = null) {
$stmt = parent::getRecordSet($sql, $params);
$recordSet = $stmt->fetchAll(PDO::FETCH_ASSOC);
$nRecords = count($recordSet);
if ($nRecords == 0) {
$status = 'error';
$message = json_encode(array("text" => "No records found"));
$result = '[]';
}
else {
$status = 'ok';
$message = json_encode(array("text" => ""));
$result = json_encode($recordSet);
}
return "{\"RowCount\": $nRecords ,\"results\": $result}";
}
}
$rs = new JSONRecordSet();
$db_conn = pdoDB::getConnection();
$stmt=$db_conn->prepare($studentUpdateSQL);
$retval=$stmt->execute(array(':surname'=>$surname,
':forename'=>$forename,
':email'=>$email,
':id'=>$id));
echo $retval;

PDO CRU are not functioning

I need your help figuring this out. I am trying to have a reserve a book functionality in my project. I don't have any error with this one but my oop functions that contains the pdo statements won't work. Particulary with the insert (values can't be inserted into the database) and update(can't update existing info from the database) part. I don't know why this happens.
bookReserve.php
<?php
session_start();
include_once "../styles/header-menu-out.php";
include_once "dbconnection.php";
function __autoload($class){
include_once("../main/".$class.".php");}
$code = new codex_books();
$sname = $_POST['sname'];
$sid = $_POST['sid'];
$id = $_POST['id'];
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
$publisher = $_POST['publisher'];
$language = $_POST['language'];
$genre = $_POST['genre'];
$quantity = $_POST['quantity'];
$date_to_be_borrow = $_POST['date_to_be_borrow'];
$result = $code->bookreserve($id,"book_info");
if(isset($_POST['reserve']))
{
foreach($result as $row)
{
echo $oldstock=$row['quantity'];
}
echo $newstock = $oldstock-1;
$code->minusbookreserve($quantity, $newstock,"book_info");
$code->insertbookreserve($sid,$sname,$title,$author,$isbn,$publisher,$language,$genre,$quantity,$date_to_be_borrow,"reserve_list");
// echo "<script type='text/javascript'>alert('Successfully Reserved.');window.location='bookReservelist.php';</script>";
}
else {
echo "<script type='text/javascript'>alert('Something went wrong.');window.location='bookReservelist.php';</script>";
}
?>
codex_books.php
public function minusbookreserve($quantity, $newstock, $table)
{
$q = "UPDATE $table SET quantity = ':newstock' where book_title = ':book_title'";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':newstock'=>$newstock, ':quantity'=>$quantity));
if($stmt){
return true;
}
else {
return false;
}
}
public function insertbookreserve($sid,$sname,$title,$author,$isbn,$publisher,$language,$genre,$quantity,$date_to_be_borrow,$table)
{
$q = "INSERT INTO $table SET sid= :sid ,sname=:sname,title=:title,author=:author,isbn=:isbn,publisher=:publisher,language=:language, genre=:genre, quantity=:quantity, date_to_be_borrow=:date_to_be_borrow";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':sid'=>$sid,':sname'=>$sname,':title'=>$title,':author'=>$author,':isbn'=>$isbn,':publisher'=>$publisher,':language'=>$language, ':genre'=>$genre,':quantity'=>$quantity,':date_to_be_borrow'=>$date_to_be_borrow));
return true;
}
Given:
$q = "UPDATE $table SET quantity = ':newstock' where book_title = ':book_title'";
^^^^^^^^^^^
Where's book_title here?
$stmt->execute(array(':newstock'=>$newstock, ':quantity'=>$quantity));
You really MUST check return values from your DB calls for boolean FALSE, indicating failure. You're simply assuming everything will always succeed, which is a very BAD way of writing code.

update mysql and add value to existing value

I am trying to edit this code so that instead of just inserting the info - it checks to see if the file already exists in the database, if it does it inserts as it does now. If it does exist... it should just update the info, adding the "value" amount to the value amount already in there instead of replacing it. But this is very new to me and I am lost so any help with really be appreciated!
<?php
define('JPATH_BASE',$_SERVER['DOCUMENT_ROOT']);
require_once($_SERVER['DOCUMENT_ROOT']."/b2/configuration.php");
require_once($_SERVER['DOCUMENT_ROOT']."/b2/libraries/joomla/factory.php");
require_once($_SERVER['DOCUMENT_ROOT']."/b2/libraries/joomla/base/object.php");
require_once($_SERVER['DOCUMENT_ROOT']."/b2/libraries/joomla/database/database.php");
require_once($_SERVER['DOCUMENT_ROOT']."/b2/libraries/joomla/database/database/mysql.php");
$config = new JConfig;
$options = array();
$options['host'] = $config->host;
$options['user'] = $config->user;
$options['password'] = $config->password;
$options['database'] = $config->db;
$options['prefix'] = $config->dbprefix;
$options['select'] = true;
$db = new JDatabaseMySQL($options);
//$user = JFactory::getUser();
$userId = 0;
//($user->id > 0) ? $user->id : 0;
$numbervote = $_REQUEST['w'];
$folder = $_REQUEST['w2'];
$name = $_REQUEST['w1'];
$date = date('Y-m-d H-i-s');
$sql = "INSERT INTO jos_image_ratetting (id,userid,datecreated,value,filename,folder,md5name) VALUES(NULL,'".$userId."','".$date."','".$numbervote."','".$name."','".$folder."',MD5('".$name."'))";
$db->setQuery($sql);
if($db->query()){
$msg = "Thanks for rate!";
}else{
$msg = mysql_error();
}
echo $msg;
//echo 'Hello';
?>
Take a look at the ON DUPLICATE KEY UPDATE syntax for MySQL

Categories