Laravel sql query is giving error while calling from ajax - php

I have reg_dental_camp table having columns id, reg_name, reg_email, reg_phone, reg_type, reg_info, created_at, updated_at
I want to fetch the table data in Laravel and show them using ajax.
The function I have written is:
public function showUsers(){
$table ="SELECT * FROM `reg_dental_camp`";
$primaryKey = 'id';
$userColumns = array(
array( 'db' => 'id', 'dt' => 'id' ),
array( 'db' => 'reg_name', 'dt' => 'reg_name' ),
array( 'db' => 'reg_email', 'dt' => 'reg_email' ),
array( 'db' => 'reg_phone', 'dt' => 'reg_phone' ),
array( 'db' => 'reg_type', 'dt' => 'reg_type' ),
array( 'db' => 'reg_info', 'dt' => 'reg_info' ),
array(
'db' => 'created_at',
'dt' => 'created_at',
'formatter' => function( $d, $row ) {
return date( 'jS M y', strtotime($d));
}
)
);
if($_SERVER['HTTP_HOST']=='localhost'){
$sql_details = array(
'user' => 'root',
'pass' => '',
'db' => 'ubl',
'host' => 'localhost'
);
}
$userResult = SSP::simple( $_GET, $sql_details, $table, $primaryKey, $userColumns);
print_r($userResult);
}
While visiting from the main page it is showing error number 500 on ajax call URL and visiting directly to the ajax call URL is is giving SQL error SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM `reg_dental_camp`
How can I solve this problem? Thanks in advance

Your are using simple method wrongly
Simple implementation from GitHub
static function simple ( $request, $conn, $table, $primaryKey, $columns )
{
$bindings = array();
$db = self::db( $conn );
// Build the SQL query string from the request
$limit = self::limit( $request, $columns );
$order = self::order( $request, $columns );
$where = self::filter( $request, $columns, $bindings );
// Main query to actually get the data
$data = self::sql_exec( $db, $bindings,
"SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
FROM `$table`
$where
$order
$limit"
);
// Data set length after filtering
$resFilterLength = self::sql_exec( $db, $bindings,
"SELECT COUNT(`{$primaryKey}`)
FROM `$table`
$where"
);
$recordsFiltered = $resFilterLength[0][0];
// Total data set length
$resTotalLength = self::sql_exec( $db,
"SELECT COUNT(`{$primaryKey}`)
FROM `$table`"
);
$recordsTotal = $resTotalLength[0][0];
/*
* Output
*/
return array(
"draw" => isset ( $request['draw'] ) ?
intval( $request['draw'] ) :
0,
"recordsTotal" => intval( $recordsTotal ),
"recordsFiltered" => intval( $recordsFiltered ),
"data" => self::data_output( $columns, $data )
);
}
So you need to provide table name only not a query. Change table variable to
$table = "reg_dental_camp"

Related

Create an odoo order and invoice it via external API

I'm trying to integrate an third party application with odoo, the application should create the order and confirm it, to generate the invoice, the order creation works perfectly, when executing the create_invoices nothing shows and no errors appears.
require_once('ripcord/ripcord.php');
$url = "http://127.0.0.1:8069";
$db = "odoo";
$password = "";
$username = "";
$common = ripcord::client("$url/xmlrpc/2/common");
$uid = $common->authenticate($db, $username, $password, array());
$models = ripcord::client("$url/xmlrpc/2/object");
$order_data = array(
'partner_id' => 12, // Customer ID
'date_order' => date('Y-m-d'), // Order Date
// 'pricelist_id' => 1, // Price List ID
'state' => 'draft', // Order Status (draft)
'order_line' => array(array(0, 0, array( // Order Line Items
'product_id' => 2, // Product ID
'name' => 'Product Name', // Product Name
'product_uom_qty' => 5.00, // Quantity of Product
'price_unit' => 10.00, // Unit Price of Product
)))
);
$order_id = $models->execute_kw($db, $uid, $password, 'sale.order', 'create', array($order_data));
// Confirm Order and Create Invoice
if ($order_id) {
$confirmOrder = $models->execute_kw($db, $uid, $password, 'sale.order', 'action_confirm', array($order_id));
if ($confirmOrder) {
$invoiceCreate = $models->execute_kw(
$db,
$uid,
$password,
'sale.advance.payment.inv',
'create_invoices',
array(
'sale_order_ids' =>
array(
0 =>
array(
0 => 6,
1 => false,
2 =>
array(
0 => $order_id,
),
),
),
'advance_payment_method' => 'delivered',
'deduct_down_payments' => true,
'product_id' => false,
'fixed_amount' => 0,
'amount' => 0,
'deposit_account_id' => false,
'deposit_taxes_id' =>
array(
0 =>
array(
0 => 6,
1 => false,
2 => array(),
),
),
)
,
array(
"context" => array(
'active_model' => "sale.order",
"allowed_company_ids" => array(1),
'active_id' => $order_id, "active_ids" => array($order_id)
)
)
);
if ($invoiceCreate) {
echo "Order and Invoice #$invoiceCreate for Order #$order_id created successfully!\n";
} else {
echo "Error creating invoice!";
}
} else {
echo "Error confirming order!";
}
} else {
echo "Error creating order!";
}
When calling create_invoices, Odoo will consider the first parameter as ids, to see the function call details change the log_level to debug
You should see the following debug message:
DEBUG demo16 odoo.api: call sale.advance.payment.inv('s', 'a', 'l', 'e', '_', 'o', 'r', 'd', 'e', 'r', '_', 'i', 'd', 's').create_invoices('advance_payment_method', 'deduct_down_payments', 'product_id', 'fixed_amount', 'amount', 'deposit_account_id', 'deposit_taxes_id')
Odoo will fail to call create_invoices function.
To fix the issue you can call the create function to get a wizard record id then call the create_invoices
Example:
$wizard_ids = $models->execute_kw(
$db,
$uid,
$password,
'sale.advance.payment.inv',
'create',
array(array(
'sale_order_ids' => array($order_id),
)),
array(
"context" => array(
'active_model' => "sale.order",
"allowed_company_ids" => array(1),
'active_id' => $order_id, "active_ids" => array($order_id)
)
)
);
$invoiceCreate = $models->execute_kw($db, $uid, $password, 'sale.advance.payment.inv', 'create_invoices', array($wizard_ids));

Laravel correct condition handling

I have a function on my site that creates a promo code for an affiliate automatically once every 24 hours. If 24 hours have passed since the creation of the promo code, it is deleted old promo from the database, and a new one is generated anew. But now there is a problem with this function, it generates a new promo code every time, regardless of whether 24 hours have passed or not.
My function:
public function autoGroupPromos()
{
$userList = Promo::get();
$userIds = $userList->pluck('user_id');
foreach ($userIds as $id) {
$date = Carbon::now();
$promoCodes = Promocode::query()->where('vk_user_id', '!=', null)->get();
foreach ($promoCodes as $promos) {
// If promo create 24 hours ago
$hours = $promos->created_at->diffInHours($date);
if ($hours >= 24) {
$promos->delete();
}
}
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
$code = substr(str_shuffle($permitted_chars), 0, 8);
Promocode::query()->create([
'name' => $code,
'sum' => '0.25',
'activates' => '100',
'vk_user_id' => $id
]);
$promoText = Promocode::where('vk_user_id', $id)->orderBy('created_at', 'desc')->first();
$promoName = $promoText->name;
$message = 'Your new promo: ' . $promoName . ';
$url = 'https://api.vk.com/method/messages.send';
$params = array(
'message' => $message,
'access_token' => 'token',
'v' => '5.81',
'peer_ids' => $id
);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params)
)
)));
}
}
That is, if less than 24 hours have passed since the promo was created - it should not be deleted and a new promo code should not be generated. But now unfortunately there is an error somewhere.
What can be the problem?
function autoGroupPromos()
{
// removed for loop to clean outdated promos in single request
// note that this way of deleting rows won't fire model events (if any)
Promocode::whereNotNull('vk_user_id')
->where('created_at', '<=', Carbon::now()->subDay(1))
->delete();
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
$userIds = Promo::pluck('user_id');
foreach ($userIds as $id) {
/* in the begining we cleaned all outdated codes, so if user still has
some - no need to create new */
if (Promocode::where('vk_user_id', $id)->exists()){
continue;
}
$code = substr(str_shuffle($permitted_chars), 0, 8);
/* you can immidiately get create model like this -
no need to make another request
$createdPromo = Promocode::create([*/
Promocode::create([
'name' => $code,
'sum' => '0.25',
'activates' => '100',
'vk_user_id' => $id
]);
/* didn't get why you were requesting newly created
promo to get name field if you put there $code value */
$message = `Your new promo: $code`;
$url = 'https://api.vk.com/method/messages.send';
$params = array(
'message' => $message,
'access_token' => 'token',
'v' => '5.81',
'peer_ids' => $id
);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params)
)
)));
}
}
upd: here can be a bit cleaner way with hasOneOfMany and skipping each user request to check if promocode exists
// User model
public function promocodes() {
return $this->hasMany(Promocode::class);
}
public function promocode() {
return $this->hasOne(Promocode::class)->latestOfMany();
}
function autoGroupPromos()
{
// note that this way of deleting rows won't fire model events (if any)
Promocode::whereNotNull('vk_user_id')
->where('created_at', '<=', Carbon::now()->subDay(1))
->delete();
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
// taking users without promo after cleanup
User::whereDoesntHave('promo')->get()
->each(function (User $user) use ($permitted_chars) {
$code = substr(str_shuffle($permitted_chars), 0, 8);
// pay attention on relation name - using hasMany
$user->promocodes()->save(
new Promocode([
'name' => $code,
'sum' => '0.25',
'activates' => '100',
])
);
$message = `Your new promo: $code`;
$url = 'https://api.vk.com/method/messages.send';
$params = array(
'message' => $message,
'access_token' => 'token',
'v' => '5.81',
'peer_ids' => $id
);
$result = file_get_contents($url, false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params)
)
)));
});
}
link Inserting & Updating Related Models

Typo 3: Create user on FE login

The situation:
I build an authentication service that uses Basic Authentication to check if the user exists on an external database and fetches some data. The users in question only exist on the external database.
The problem:
Typo3 needs to have an user entry in the fe_user table to login the user.
So whenever this entry does not exist, the user cannot login.
What I want to do:
Create the user in the authentication service to avoid using a sql dump from the external database and ensure that synchronisation is possible.
The relevant code:
public function authUser(array $user) {
$a_user = $this->login['uname'];
$a_pwd = $this->login['uident_text'];
$url = 'https://soliday.fluchtpunkt.at/api/queryMediaItems';
$data = json_decode('{"language":"de-at"}');
$basicAuth = base64_encode("$a_user:$a_pwd");
// use key 'http' even if you send the request to https://...
$options = array (
'http' => array (
'header' => array(
"Content-Type: application/json",
"Accept: application/json",
"Authorization: Basic {$basicAuth}"
),
'method' => 'POST',
'content' => '{"language":"de-at"}'
)
);
$context = stream_context_create ( $options );
$result = file_get_contents ($url, false, $context);
$response = gzdecode($result);
$checkUser = $this->fetchUserRecord ( $this->login ['uname'] );
if (!is_array($checkUser)&& $result!== FALSE) {
$this->createUser();
}
// failure
if ($result === FALSE) {
return static::STATUS_AUTHENTICATION_FAILURE_BREAK;
}
$this->processData($response);
// success
return static::STATUS_AUTHENTICATION_SUCCESS_BREAK;
}
public function createUser() {
$username = $this->login ['uname'];
$password = $this->login ['uident_text'];
$record = $GLOBALS ['TYPO3_DB']->exec_SELECTgetSingleRow ( '*', 'fe_users', "username = '" . $username . "' AND disable = 0 AND deleted = 0" );
if (! $record) {
// user has no DB record (yet), create one using defaults registered in extension config
// password is not important, username is set to the user's input
$record = array (
'username' => $username,
'password' => $password,
'name' => '',
'email' => '',
'disable' => '0',
'deleted' => '0',
'pid' => $this->config ['storagePid'],
'usergroup' => $this->config ['addUsersToGroups'],
'tstamp' => time ()
);
if (t3lib_extMgm::isLoaded ( 'extbase' )) {
$record ['tx_extbase_type'] = $this->config ['recordType'];
}
$GLOBALS ['TYPO3_DB']->exec_INSERTquery ( 'fe_users', $record );
$uid = $GLOBALS ['TYPO3_DB']->sql_insert_id ();
$record = $GLOBALS ['TYPO3_DB']->exec_SELECTgetSingleRow ( '*', 'fe_users', 'uid = ' . intval ( $uid ) );
}
$_SESSION [$this->sessionKey] ['user'] ['fe'] = $record;
}
the ext_localconf.php file:
<?php
if (!defined('TYPO3_MODE')) {
die ('Access denied.');
}
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addService(
$_EXTKEY,
'auth' /* sv type */,
'AuthService' /* sv key */,
array(
'title' => 'GET Authentication service',
'description' => 'Authenticates users with GET request.',
'subtype' => 'getUserFE, authUserFE',
'available' => true,
'priority' => 90,
'quality' => 90,
'os' => '',
'exec' => '',
'className' => Plaspack\professionalZoneLogin\Service\AuthService::class,
)
);
You should extend AuthenticationService with your own code, way of doing that is described here https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Xclasses/Index.html
Not sure if it's related, but t3lib_extMgm should be \TYPO3\CMS\Core\Utility\ExtensionManagementUtility unless you're using TYPO3 6.
You can also see if you get any SQL errors by calling $GLOBALS['TYPO3_DB']->sql_error().

PHP code function not working properly

I have a PHP file where I use the following PHP code to access my DB to retrieve some data to create a geojson. It does return a geojson but all html etc is exluded when i call this function.
<?php
require_once("db.php");
$geo = connectToDB::getGeoJSON();
?>
This is the function im calling from another a db.php file.
public static function getGeoJSON() {
$db_connection = new mysqli(mysqlServer, mysqlUser, mysqlPass, mysqlDB);
$statement = $db_connection->prepare("Select poiId, lat,lng,description from poi");
$statement->bind_result( $id, $lat, $lng, $description);
$statement->execute();
$feature = array();
$geojson = array(
'type' => 'FeatureCollection',
'features' => $feature
);
while ($statement->fetch()) {
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array($lng, $lat)
),
'properties' => array(
'description' => $description
//Other fields here, end without a comma
)
);
array_push($geojson, $feature);
}
$statement->close();
$db_connection->close();
//Return routing result
header("Content-Type:application/json",true);
return $geojson;
}
Can anyone see whats wrong with the code? It does return the correct output but then the rest of the page wont show. Other functions I call is working normally so its the geojson function something is wrong with.

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`=?"

Categories