Error when rendering .tpl file from SQL query - mysql

I'm trying to get a result from a MySQL database and display selected values into a .tpl template file.
This is what I tried so far:
{php}
$clienthosting = $this->get_template_vars(service);//Here is where the exception is thrown
$dbid = $clienthosting['id'];
$query = mysql_query("SELECT dedicatedip FROM tblhosting WHERE id = $dbid");
$result = mysql_fetch_array($query);
$dedicatedip = $result["dedicatedip"];
$this->assign("dedicatedip", $dedicatedip);
{/php}
But it generated the following error:
Something went wrong and we couldn't process your request.
What am I doing wrong?
Thanks.

WHMCS recommends not use {php} inside tpl files, you can use hooks instead to add variables and use them in the TPL file.
But you can enable it in the settings: Setup > General Settings > Security > Allow Smarty PHP Tags.
Also, if you're running PHP 7 the mysql extension is removed, you can't use functions like mysql_query and mysql_fetch_array.
You should use Capsule and Eloquent as recommended at Interacting with the Database page

Related

Laravel sql insert is not working properly via DB::unprepared

I get SQL via file_get_contents and give DB::unprepared function
$path = public_path('sql/Store.sql');
$sql = file_get_contents($path);
DB::unprepared($sql);
the tables are created but the triggers are not created.
But when I put this SQL code to phpMyadmin both tables and triggers are created successfully. I use Server version: 10.3.28-MariaDB - MariaDB Server.
Do you have any idea how to solve this issue?
You should trim the contents that come from the file to remove some characters like \n at the end of sqls. I've used trim($file_path, "\x00..\x1F") to remove this range of characters from your sql.
$path = public_path('sql/Store.sql');
$sql = trim(file_get_contents($path), "\x00..\x1F");
DB::unprepared($sql);

find the path to the script which is running the query

is there any query to return information about the current script that is running it ?
like for example if i have a file in
/home/domain/public_html/script.php
i want to put a query in it that file to return the filename and path i.e :
/home/domain/public_html/script.php
or at least the base path to it ]
/home/domain/public_html/
pleas note i know lots of method to do this but i specifically want to get these information back from database in response and after running a query
No, there is no way for the MySQL Server to know the name or path to the PHP script that is executing queries unless you tell it.
I've seen some projects that establish a coding practice to append a comment to the SQL queries with information to help you identify the source.
SELECT * FROM MyTable WHERE id = 123; /* File: script.php, Function: myFunction() */
You then see these comments appearing in the MySQL processlist, and in query logs.
You have to write code to put the comment into the SQL yourself:
$sql = sprintf("SELECT * FROM MyTable WHERE id = 123; /* File: %s, Function: %s() */",
__FILE__, __FUNCTION__);
If you don't want to change the code, another great solution is to use New Relic Application Monitoring, which tracks SQL queries in code for you, without any need to modify your code. It's costly to pay for the New Relic service, but it's the best solution. If you want to explore cheaper alternatives, search google "alternatives to new relic".

How to resolve SQL table with prefix in PhpStorm?

I'm working on PhpStorm to develop my Prestashop websites and I can't resolve this issue. I work on localhost and successfully connected PhpStorm to my MySQL Server.
Now PhpStorm throws warnings like "unable to resolve table '${_DB_PREFIX_}cms'". Prestashop uses prefixes for table names and it seems PhpStorm can't resolve those tables with prefixes.
Is there a workaround for this ?
Here is a code exemple from Prestashop-1.6 sources :
$sql = 'SELECT c.`id_cms`, cl.`meta_title`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms` c
INNER JOIN `'._DB_PREFIX_.'cms_shop` cs
ON (c.`id_cms` = cs.`id_cms`)
INNER JOIN `'._DB_PREFIX_.'cms_lang` cl
ON (c.`id_cms` = cl.`id_cms`)
WHERE c.`id_cms_category` = '.(int)$id_cms_category.'
AND cs.`id_shop` = '.(int)$id_shop.'
AND cl.`id_lang` = '.(int)$id_lang.
$where_shop.'
AND c.`active` = 1
ORDER BY `position`';
The reason why this isn't work is because you are most likely only loading one schema, you need to load the information_schema.*
To do this, go to the database tab in the top right and where you have added your MySQL database right click and select properties.
Now you'll have a screen called Data Sources and Drivers, it should open on a tab called General, click the third tab called Schemas and and add information_schema.* to this list of loaded Schemas.
Click apply and okay and then PhpStorm will now know your database structure and then be intelligently able to work with you, therefor removing all the errors.
Edit: As mentioned here, this has been fixed in PhpStorm 2018.2, but only for constants.
I have a solution that doesn't involve throwing your IDE away. :)
However, a word of caution: it's an ugly hackā„¢ that comes without guarantees.
Assuming you already have a connection to the db in PhpStorm, generate the ddl for the desired db (Right Click on the connection -> SQL Scripts -> Generate DDL to Clipboard):
Paste the content into some sql file somewhere inside your project. You should probably gitignore this file.
Replace all the tables' prefix in this ddl file with the one from your code. Use the PhpStorm typehint as a guideline. For example '._DB_PREFIX_.'cms would become ${_DB_PREFIX_}cms:
Note that you may have to use backticks to avoid breaking sql syntax due to curly brackets.
Add the ddl to your phpstorm project:
Everything should now work:
Add this comment above the $sql query.
/** #noinspection SqlResolve */
This will suppress the warning only for this statement.
For future readers, this is now supported:
https://www.jetbrains.com/help/phpstorm/2021.1/ide-advanced-metadata.html#set-up-dynamic-prefixes-for-table-names-in-sql-language-injections
.phpstorm.meta.php
<?php
namespace PHPSTORM_META {
override(
// Virtual function to indicate that all SQL
// injections will have the following replacement rules.
sql_injection_subst(),
map([
'{' => "", // all `{` in injected SQL strings will be replaced with a prefix
'}' => '', // all `}` will be replaced with an empty string
]));
}
Edit: At time of writing (2016) there was no solution to this issue. But since 2018, as mentioned in Christian's answer, you can now use constants in SQL queries.
Actually there is no way to handle that. But you may disable inspection for such warning.
Open File > Settings > Editor > Inspections
Expand SQL
Uncheck Unresolved reference

How to pass a where clause simply but safely via a console command in ZF2?

I'm creating a quick and dirty console controller to create fixtures from a database table.
I'd like to use a where clause to limit this - but would like to make the controller a little less dirty and prevent injections.
My current console command specification is:
db create fixture <table_name> [--where=]
The controller action has:
$tableName = $request->getParam('table_name');
$where = $request->getParam('where');
$queryString = "select * from `$tableName`";
if (!is_null($where)) {
$queryString .= " where $where";
}
$resultSet = $dbAdapter->query(
$queryString,
DbAdapter::QUERY_MODE_EXECUTE
);
Now, I know this is obviously wide open to SQL injection - as confirmed when I ran the following:
db create fixture hit_log --where="\`timestamp\` between '2015-01-20 00:00:00' and '2015-01-30 00:00:00'; delete from hit_log limit 1";
So, what would be a good strategy to fix this?
I'm thinking of JSON notation --where='{"timestamp":["between","2015-01-20","2015-02-30"]}' - but then I'll have to write a translator to handle different tests like "=", "LIKE", and "BETWEEN".
Edit:
I've put checks in the controller action to ensure it is a console only request, and will error out if a user somehow manages to route via the http router.
This then assumes that a developer is running the command, and would have access to the database anyway. I guess this is more trying to protect against error than malice.

Zend appendFIle tweaking

How can I include a same .js file multiple times but it will add it to the header only once. The idea is similar to include and include_once function in PHP. I am using the following zend framework function. And idea would be appreciated.
appendFile($src, $type = 'text/javascript', $attrs = array())
There are two possibilities:
Extend Zend_View_Helper_HeadScript and loop through the container ($view->headScript()->getContainer()) to check whether the file already exists
Before rendering the headScript(), retrieve the container and filter out duplicates.