mysql_real_escape_string(): Access denied in DB insert - mysql

I am trying to use a legacy MediaWiki extension on PHP 5.6 and later versions, and it fails when it comes to DB inserts.
And yes, this is not a duplicate, as the code is different.
The full error was:
Warning: mysql_real_escape_string(): Access denied for user
''#'localhost' (using password: NO)
I tried changing to mysqli_real_escape_string but then I had:
mysqli_real_escape_string() expects exactly 2 parameters, 1 given on
line 235
Here is the function:
function Lookup_addLookup ($url, $name, $group)
{
$dbw = wfGetDB(DB_MASTER);
$groupOrder = Lookup_getGroupOrder($group);
$dbw->query ("INSERT INTO ".Lookup_prefix()."lookups (lu_name, lu_url, lu_group, lu_order, lu_group_order) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($url)."', '".mysql_real_escape_string($group)."', 1, $groupOrder)");
Lookup_reOrderGroups();
return true;
}
And another one further down:
function Lookup_moveGroupUp($group)
{
$dbw = wfGetDB(DB_MASTER);
$dbw->query ("UPDATE ".Lookup_prefix()."lookups SET lu_group_order = 0 WHERE lu_group = '".mysqli_real_escape_string($group)."'");
Lookup_reOrderGroups();
return true;
}

mysqli_real_escape_string() needs the database link as the first parameter, which is why it isn't working.
However, MediaWiki wants us to avoid direct queries, so it has the $dbw->insert() method instead, one of several wrapper functions.
Use something like this:
function Lookup_addLookup ($url, $name, $group)
{
$dbw = wfGetDB(DB_MASTER);
$groupOrder = Lookup_getGroupOrder($group);
$dbw->insert(
Lookup_prefix()."lookups",
array(
'lu_name' => $name,
'lu_url' => $url,
'lu_group' => $group,
'lu_order' => 1,
'lu_group_order' => $groupOrder
)
);
Lookup_reOrderGroups();
return true;
}
And in the second example, use $dbw->update():
function Lookup_moveGroupUp($group)
{
$dbw = wfGetDB(DB_MASTER);
$dbw->update(
Lookup_prefix()."lookups",
array(
"lu_group_order" => 0
),
array(
"lu_group" => $group
)
);
Lookup_reOrderGroups();
return true;
}
For more information and other SQL wrappers, read about the different wrapper functions and their documentation.

Related

Insert query works fine on my local but doesn't execute on my live database (Laravel/MySQL)

I have a very simple function that loops through an array and inserts some data into a results table - this works perfectly fine on my local using the very same code. On my local setup (Mac) using Laravel Valet & an MySQL database it hits the function Result::create($data) and inserts this data in the database. However on the live/remote site it never hits the Result::create() within the insertUniqueMatches for some reason.
I have added the db user in the env file and it has been granted all privileges so I cannot understand why this won't insert the entry into the results table. Can anyone explain what I am doing wrong? All migrations have been ran to ensure my local and live db are identical.
P.S i have tried both the $fillable variable with all the relevant items in the array and also with the $guarded as a blank array and the problem persists.
class Result extends Model
{
use HasFactory;
// protected $fillable = ['match_id', 'home_team_id', 'away_team_id', 'home_team_goals', 'away_team_goals', 'outcome', 'match_date', 'properties', 'platform_id'];
protected $guarded = [];
public static function insertUniqueMatches($matches, $platform = null)
{
$inserted = 0;
foreach ($matches as $match) {
// check if existing match already exists in the db, if so don't re-insert this
if (Result::where('match_id', '=', $match['matchId'])->doesntExist()) {
$carbonDate = Carbon::now();
$carbonDate->timestamp($match['timestamp']);
$clubs = collect($match['clubs'])->values();
$data = [
'match_id' => $match['matchId'],
'home_team_id' => $clubs[0]['id'],
'away_team_id' => $clubs[1]['id'],
'home_team_goals' => $clubs[0]['goals'],
'away_team_goals' => $clubs[1]['goals'],
'outcome' => self::getMatchOutcome($clubs[0]),
'match_date' => $carbonDate->format('Y-m-d H:i:s'),
'properties' => json_encode([
'clubs' => $match['clubs'],
'players' => $match['players']
]),
'platform_id' => $platform
];
dump($data); // this shows valid data in the terminal
// this if condition is only reached on my local development but never on live so no inserts happen on the live DB
if (Result::create($data)) {
$inserted++;
dump('inserted matchId: '. $match['matchId']); // never see this on line but always on local
}
}
}
return $inserted;
}
i think better solution for now is you can find the problem.
you could write code into try-catch for more information.
replace this code
try {
Result::create($data);
} catch (\Exception $e) {
dd($e);
}
with:
dump($data); // this shows valid data in the terminal
// this if condition is only reached on my local development but never on live
if (Result::create($data)) {
$inserted++;
dump('inserted matchId: '. $match['matchId']); // never see this on line but always on local
}

Updating record from PHP Client library for Exact Online

I had used PHP Client library for Exact Online.
I need to store the record, based on the condition if it exists or not. Since records are saving successfully. But unfortunately records are not updating.
$customer = [
'address' => 'No.22/N, 91 Cross, XYZ Street, ABC Road',
'address2' => 'DEF',
'city' => 'GHI',
'customerid' => '999',
'country' => 'DE',
'name' => 'Nishanth',
'zipcode' => '123456'
];
// Create a new account
$account->AddressLine1 = $customer['address'];
$account->AddressLine2 = $customer['address2'];
$account->City = $customer['city'];
$account->Code = $customer['customerid'];
$account->Country = $customer['country'];
$account->IsSales = 'true';
$account->Name = $customer['name'];
$account->Postcode = $customer['zipcode'];
$account->Email = 'nishanth#gmail.com';
$account->Status = 'C';
From the above piece of code, based on the condition the record needs to be updated or saved from the below coding snippets. Followed two approaches:
I Approach:
if($AccInfo)
{ // Update
$AccInfo->AddressLine1 = $customer['address'];
$AccInfo->AddressLine2 = $customer['address2'];
$AccInfo->City = $customer['city'];
$updateAcc = $AccInfo->update();
}
else
{ // Save
$savedAcc = $Accounts->save();
}
Result:
Warning: Attempt to assign property 'AddressLine1' of non-object in E:\xampp\htdocs\exact-php-client-master\example\example.php on line 506
Warning: Attempt to assign property 'AddressLine2' of non-object in E:\xampp\htdocs\exact-php-client-master\example\example.php on line 507
Warning: Attempt to assign property 'City' of non-object in E:\xampp\htdocs\exact-php-client-master\example\example.php on line 508
Fatal error: Uncaught Error: Call to a member function update() on array in E:\xampp\htdocs\exact-php-client-master\example\example.php:510 Stack trace: #0 {main} thrown in E:\..\..\exact-php-client-master\example\example.php on line 510
II Approach:
if($AccInfo)
{ // Update
$updateAcc = $Accounts->update();
}
else
{ // Save
$savedAcc = $Accounts->save();
}
Result:
Picqer\Financials\Exact\ApiException : Error 400: Bad Request - Error in query syntax.
How should we need to update the records to Exact Online Dashboard?
Finally I solved the issue by writing custom methods
$AccInfo = $Accounts->filter("Email eq 'nishanthjay#gmail.com'");
if($AccInfo)
{ // Update
$updateAcc = $Accounts->customUpdate($AccInfo[0]->ID);
echo '<pre>'; print_r($updateAcc);
}
else
{ // Save
$savedAcc = $Accounts->save();
}
I had written my own methods from ..\src\Picqer\Financials\Exact\Persistance\Storable.php
public function customUpdate($primaryKey='')
{
$this->fill($this->update2($primaryKey));
return $this;
}
public function update2($primaryKey='')
{
return $this->connection()->put($this->url() . "(guid'$primaryKey')", $this->json());
}
For any one who knows exactly how to update to an ExactOnline. You are always welcome to answer to the posted question via built-In function call known as update().

Laravel: Store error messages in database

Any one know how to send error messages to database in laravel which generate from app/exceptions/handler.php ?
I need to send what error massages generated in report() method to database.
If you are interested doing this manually, you can do something as following.
Step 1 -
Create a model to store errors that has a DB structure as following.
class Error extends Model
{
protected $fillable = ['user_id' , 'code' , 'file' , 'line' , 'message' , 'trace' ];
}
Step 2
Locate the App/Exceptions/Handler.php file, include Auth, and the Error model you created. and replace the report function with the following code.
public function report(Exception $exception) {
// Checks if a user has logged in to the system, so the error will be recorded with the user id
$userId = 0;
if (Auth::user()) {
$userId = Auth::user()->id;
}
$data = array(
'user_id' => $userId,
'code' => $exception->getCode(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'message' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
);
Error::create($data);
parent::report($exception);
}
(I am demonstrating this using laravel 5.6)
Because Laravel uses Monolog for handling logging it seems that writing Monolog Handler would be the cleanest way.
I was able to find something that exists already, please have a look at monolog-mysql package. I did not use it, so I don't know whether it works and if it works well, but it's definitely good starting point.

Error: SQLSTATE[42000]: Syntax error or access violation with cakePHP

I am using the framework cakePHP for my application. I programmed it on localhost with xampp and try to upload it on my website now. It worked without any problems on localhost. Now there is only this one page, which does not work on the new server. The other sites (which use the database connection too) work alright.
For this one site the following message appears:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'add' at line 1
SQL Query: add
The function add() looks like this.
public function add() {
//$this->create();
$word_id = $this->Word->getWord_id();
$save = $this->save(array('word_id' => $word_id, 'text' => $this->getText($word_id), 'mistake' => 0));
return $save['Game']['id'];
}
On localhost I used MySQL-Client-Version: mysqlnd 5.0.8-dev - 20102224 - $Revision: 310735 $ and PHP Version 5.3.8.
On the server I use MySQL-Client-Version: 5.1.62 and PHP Version 5.3.17.
Thank you very much for helping!
Edit:
The model 'Game':
class Game extends AppModel {
public $name = 'Game';
public $belongsTo = 'Word';
public $searchedWord = '';
public function addGame() { // Create new game
$word_id = $this->Word->getWord_id();
$save = $this->save(array('word_id' => $word_id, 'text' => $this->getText($word_id), 'mistake' => 0));
return $save['Game']['id']; // Build the hangman
}
}
When I debug $this->Game, the output is:
object(AppModel) {
useDbConfig => 'default'
useTable => 'games'
id => null
data => array()
schemaName => null
table => 'games'
primaryKey => 'id'
validate => array()
validationErrors => array()
validationDomain => null
name => 'Game'
alias => 'Game'
tableToModel => array(
'games' => 'Game'
)
cacheQueries => false
belongsTo => array()
hasOne => array()
hasMany => array()
hasAndBelongsToMany => array()
actsAs => null
Behaviors => object(BehaviorCollection) {
modelName => 'Game'
defaultPriority => (int) 10
}
whitelist => array()
cacheSources => true
findQueryType => null
recursive => (int) 1
order => null
virtualFields => array()
__backAssociation => array()
__backInnerAssociation => array()
__backOriginalAssociation => array()
__backContainableAssociation => array()
findMethods => array(
'all' => true,
'first' => true,
'count' => true,
'neighbors' => true,
'list' => true,
'threaded' => true
)
}
usually, if this error happens, you don't have the model instance, but an app model instance you work on. the app model instance doesnt have the add() method and directly queries the db with add().
so make sure your model is properly included. since you didnt show us the code how you call the method (and how you make the model available to the controller) I cannot offer any concrete advice, though.
if you manually include it:
$this->ModelName = ClassRegistry::init('ModelName');
add is a reserved word in MySQL and you're probably using it in a SQL query without "escape".
Check if you have any field named add in your database.
I just had this error and I felt pretty stupid. I'm sure this has been solved a long time ago, but in case anyone else comes across it...
Using your example I'll show basically what I also stupidly did in my Controller and how it caused the same type of error you had:
public function index($gameid = null, $letter = null) {
if ($gameid == null) {
// New game
$gameid = $this->Game->addGame();
}
}
Since you already have the instance (controller class) and you're not calling the Model method of addGame here, but the Controller's method, you simply remove the Game-> from your one-line command.
$gameid = $this->addGame();
Simple and easy oversight. That said, if you moved the addGame method to your Model class, it probably would have worked as expected. :)

Trouble insert date form to mysql in drupal 7

hi im having little trouble at inserting date from drupal to mysql
here the code that i'm trying
.....
$form['kotak']['tgl'] = array(
'#type' => 'date',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
everytime i'm submit, error code like this
db_insert failed. Message = SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1, query= INSERT INTO {jp_1} (tanggal) VALUES (:db_insert_placeholder_0_month, :db_insert_placeholder_0_day, :db_insert_placeholder_0_year)
any suggestion or correction?
From the mysql error it looks like the table you created has required fields (a columns Null property is set to 0, which means that there must be a value for tha column for every row you want to insert)
Check whether there are any columns which have null set to 0.
From your example I can't see what you're trying to achieve, but in many cases it's not necessary to write into db tables manually (using db_insert()) as you can get the same result easier by creating a content type (node type) which handles a lot of functionality for you.
I hope that helps, Martin
i'm finally managed to find the answer, all i need is download "Date" module and activate its "Date API". Here the code
.....
$datex = '2005-1-1';
$format = 'Y-m-d';
$form['kotak']['tgl'] = array(
'#type' => 'date_select',
'#default_value' => $datex,
'#date_format' => $format,
'#date_year_range' => '-10:+30',
'#title' => t('Tanggal'),
);
.....
function awal_form_submit($form,&$form_state){
global $user;
$entry = array(
'tanggal' => $form_state['values']['tgl'],
);
$tabel = 'jp_1';
$return = insert_form($entry,$tabel);
}
.....
function insert_form($entry,$tabel){
$return_value = NULL;
try {
$return_value = db_insert($tabel)
->fields($entry)
->execute();
}
.....
and now i have no problem delivering to mysql.
Hope that will help other drupal newbie developer like me. Thanks :D