Store a variable as variable in database - php

Hello im building a multilenguaje app in php, this is the first time i handle multilenguaje, im trying to do it like this.
For months for example
i have a table "months" with id | month estructure
in the users table i have id | username | month_id
my guess (bad guess) its that i can save for example $january direct on the database so in the php when its called, it looked for the defined variable.
$january = "january"; and if im on spanish web then i change this to $january = "Enero";
but this is not working (obviusly because it prints as a result of a call $january, Its saved as $january in the database)
How is the best method for what im trying to do.. cause im lost in this point.. and i need this estructure in the database for a lot of reasons i wont mention, right now,
thanks!
My code
This $row2['months']
Print this $january
Even when in the php code i have set $january = "enero";

You might rethink your strategy.
Example:
For 10 languages if you keep 10 php files defining the month names or actually all language locale words in, it will be sufficient and you can include them without disturbing the database.
<?php
// this is words_en.php, you can make another like words_de.php etc.
$months = array('january','february','march','april'....etc );
?>
If you structure your locale file consistently for instance:
$msgs = array(
'MSG1'=>'first message',...
}
keeping only the references(like'MSG1') in your code and also in your database will be sufficient. For the months, you can keep them apart from $msgs since their use is specific and numeric indexing adds more consistency to coding for their case.
Note that this is not the only method for language locales but this is an easy to maintain version.

You should save the users locale e.g. en_US in your table and base further translations on that value with a fallback to the default language.

To get php to evaluate that variable, what you need to do is eval:
$january='Enero';
$row='$january';
echo $row; //Prints $january
echo PHP_EOL;
echo eval("return ".$row.";"); //Prints Enero
Here that is in ideOne: http://ideone.com/f0LCT0

Related

PHP, Add gmdate to gmdate

I have a code that looks like this:
$dagtidhelg = gmdate('H:i', $diffMorning) . "\n";
$kvallstidhelg = gmdate('H:i', $diffNight);
This code runs several times per page since its runt every time a row is loaded from mysql.
It can return a time value ie 08:15 and 09:30. This is the lenght of two work sessions.
That works great but now Im stuck, I want to display the total of every work session at the bottom. I have tried this:
$dagtidhelgtotal = $dagtidhelgtotal + $dagtidhelg;
$kvalltidhelgtotal = $kvalltidhelgtotal + $kvallstidhelg;
But that only adds the hours togheter, it wont even display the :
So Im guessing that Im doing this totaly wrong.
How can I add these times togheter? Maybe convert them to minutes, then add them all togheter?
Add duration together is simple .But you must keep in mind that duration and date are two things completely different. You can write 100:08 for duration but not for date. If your purpose is to keep a duration counter on(one or) every page(s) you need to build a system based on $_SESSION variable.
To add two duree you can proceed like this:
function addDuration($duration1,$duration2){
$result=array_map(function($x,$y){return sprintf("%'.02d", $x+$y);},explode(':',$duration1),explode(':',$duration2));
if($result[1]>60){
$result[0]=sprintf("%'.02d",$result[0]+(int)$result[1]/60);
$result[1]=sprintf("%'.02d",$result[1]%60);
}elseif($result[1]==60){
$result[1]="00";
$result[0]=sprintf("%'.02d",$result[0]+1);
}
return join(':',$result);
}
and the usage in your case could be:
$dagtidhelgtotal = addDuration($dagtidhelgtotal,$dagtidhelg);
if we suppose that
$dagtidhelgtotal ==='100:09' && $dagtidhelg === '08:08'
then after the addition
$dagtidhelgtotal will be equal to '108:17';

PHP get multilanguage data from database with instant variables

What I would like is to store every word / sentence / ... in a database tabel like so:
Table name:
translate
columns:
id, var, dutch, english, french
Example:
'1', 'titleOne', 'Hallo Wereld!', 'Hello World!', 'Bonjour le monde!'
What I would like is to print the variable for example at the title section:
<?php
echo $titleOne;
?>
Since there will be hundreds of lines I do not want to set $titleOne = $row['titleOne'] for every line.
Can someone please help me out with a nice query, pull, fetch, array, loop, ... however you call this? (or a nice alternative way is also good!)
This is plain PHP, no frameworks are used.
PS: I am not a PHP expert at all so please try to keep it simple :-)!
Thanks a lot!
I 2nd the advice given by others about your table structure, but to answer your question you can use extract
$row = array(
col_1 => 'a',
col_2 => 'b',
col_3 => 'c'
)
extract($row);
// results in:
// $col_1 assigned value 'a'
// $col_2 assigned value 'b'
// $col_3 assigned value 'c'
To answer your question directly. You could query your current setup as follows:
-- For Dutch (pseudocode)
$query = 'SELECT var, dutch FROM translate';
$translations = array();
while loop ($row = $query) {
$translations['var'] = $row['dutch'];
}
// Then, to access translations you would:
echo $translations['titleOne'];
BUT you don't want to do this. This table structure will lead you down a path of regret. Heed our warnings. There are many ways to go about this and you've chosen to go the SQL route so here are some tips.
Change your table structure so you don't have to add a new column each time you add a new language.
Table: languages (Add a new row to support a new language)
id, locale, language
1, en_CA, English
2, en_US, English
3, en_UK, English
4, es_ES, Spanish
5, es_MX, Spanish
...
Table: translations (add a new row to add a translation)
id, locale, translation_key, translation
1, en_CA, 'hello', 'Hi from Canada'
2, en_US, 'hello', 'Hi from the US'
3, en_UK, 'hello', 'Hi from the UK'
4, es_ES, 'hello', 'Hi from Spain'
5, es_MX, 'hello', 'Hi from Mexico'
...
translations.locale should be a foreign key pointing back to languages but I'm not sure what your SQL level is so leaving it as clear as I know how.
I assume you can figure out how to query your database from PHP. What you want to do is:
figure out which locale to use. This will be one of the trickiest parts. Ex. should you be using the one specified in the URL, the session, the browser setting? What happens if none of those is specified? What is the fallback locale? See my getLanguage() function in https://stackoverflow.com/a/49758067/296555 for some ideas.
Pull all translations for that locale and store them in memory. Here is a basic query to pull all translations for a given locale.
<?pseudocode
$locale = 'en_CA';
// Find all translations for a given locale
$dbQuery = 'SELECT translation_key, translation
FROM translations
WHERE locale = :locale';
;
Put those entries you just pulled in to memory.
<?pseudocode
$translations = array();
while loop ($row = $dbQuery) {
$translations[$row['translation_key']] = $row['translation'];
}
Throughout your application, you can now access translations via that array.
echo $translations['hello'];
You'll want to do this high up in your application in a part that is called on every request. Once you have this going you will want to start optimizing. You could store the database results to the session so you don't have to query the DB on each page load or implement a more robust form of caching.
In all honesty, I think you have the right idea but the devil is in the details or so they say. Read the link that I pointed to. It isn't perfect but it should help you get to a workable solution relatively quickly.

PHP/MySQL/PDO search on date from database

Trying to make a little Search feature for a user, so he can type in a date on a webpage made with HTML/PHP, and see which people in the db have registered as member on or after (a date). My user inputs the date in format 2015-10-01. This gets sent to a PHP page with a jqxGrid on it, populated with member details of members conforming to my query on the MySQL database (using PDO).
The query uses the operator >= on a string passed as (for example) "2015-10-01" in the WHERE clause, so I am using STR_TO_DATE to make the comparison work:
WHERE `lastUpdated` >= STR_TO_DATE( ? , '%Y-%m-%d');
With PDO, the ? later gets bound to the date (which was passed in as a string).
The db column for registration date is in DATETIME format, and in the db values look like: "2015-10-12 17:12:52".
My query returns an empty array every time, - and this after many hours of trying every conceivable permutation of date format, both in the MySQL statement and on the page that prepares the data for populating the grid.
Can someone show me what's wrong here?
Thanks!!
SP
Make it
WHERE `lastUpdated` > ?
and check your data and stuff.
Basically, you should never touch PDO until you get raw SQL to work.
okay, so here is the PDO version that works - passing in ? instead of the date:
function getJSONAllMembersByDate($PDOdbObject, $regDate)
{
try
{
$membersByDateSQL = "SELECT `id`, `name_first`, `name_last`, `organization`,`email`, `phone`,`source`,`comments`,`language_id`, `lastUpdated` FROM `member` WHERE lastUpdated>=?";//'$regDate'
$get=$PDOdbObject->prepare($membersByDateSQL);
$get->execute(array($regDate));
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($rows);
return $json;
}
The fact that it works proves there were other errors in the file containing the jqxwidget (the version before I posted here). I certainly tried about a million different things to get this working.
I don't know if this counts as an answer, but at least it WORKS! There are so many variables in this problem - json, jqxgrid, pdo ... not forgetting that there are several ways to use PDO. I probably had several errors in different places.
(#apokryfos, the STR_TO_DATE was indeed unnecessary.)
In the end, this is what works:
In the PHP page containing the jqxGrid, the url sent to the server is:
url: 'my-json-responses.php?fct=getJSONAllMembersByDate&regDate=<?php echo $fromDate ?>'
This $fromDate comes from the $_POST when the user typed in a date (in the format 2015-10-01) on the input page. When the PHP page containing the jqxGrid loads, it does
$fromDate = $_POST['regDate'];
The url "transits" through the file my-json-reponses.php, which contains many functions. It finds the right one:
if ($_GET['fct'] == 'getJSONAllMembersByDate')
{
$result = getJSONAllMembersByDate($connectionObject, $_GET['regDate']);
echo $result;
}
The $result is called on the file that contains all my PDO database requests, including:
function getJSONAllMembersByDate($PDOdbObject, $regDate) { try
{
$membersByDateSQL = "SELECT `id`, `name_first`, `name_last`, `organization`,`email`, `phone`,`source`,`comments`,`language_id`, `lastUpdated` FROM `member` WHERE lastUpdated>='$regDate'";
$get=$PDOdbObject->query($membersByDateSQL);
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($rows);
return $json;
}
catch (PDOException $e)
{
echo "There was a problem getting all members with this search query.";
echo $e->getMessage();
}}
Note that I couldn't make the version using "?" in the query work at all, hence passing in the variable $regDate directly, with single quotes around the variable just to make life interesting.
This returns a nice list of all my users as of 2015-10-01 - but is presumably still open to MySQL injection attacks ...
But after this marathon of debugging I am happy enough for now. (All improvements welcomed, naturally!)
SP

Help setting up logic for advanced search parameters in PHP

I would like to create an advanced search form much like a job site would have one that would include criteria such as keyword, job type, min pay, max pay, category,sub category etc...
My problem is deciding on how best to set this up so if I have to add categories to the parameters I'm not having to modify a whole bunch of queries and functions etc...
My best guess would be to create some sort of associative array out of all of the potential parameters and reuse this array but for some reason I feel like it's a lot more complex than this. I am using CodeIgniter as an MVC framework if that makes any difference.
Does anybody have a suggestion as how best to set this up?
Keep in mind I will need to be generating links such as index.php?keyword=designer&job_type=2&min_pay=20&max_pay=30
I hope my question is not to vague.
I don't know if it's what you need, but I usually create some search class.
<?php
$search = new Search('people');
$search->minPay(1000);
$search->maxPay(4000);
$search->jobType('IT');
$results = $search->execute();
foreach ($results as $result)
{
//whatever you want
}
?>
You can have all this methods, or have some mapping at __set() between method name and database field. The parameter passed to the constructor is the table where to do the main query. On the methods or mapping in the __set(), you have to take care of any needed join and the fields to join on.
There are much more 'enterprise-level' ways of doing this, but for a small site this should be OK. There are lots more ActiveRecord methods you can use as necessary. CI will chain them for you to make an efficient SQL request.
if($this->input->get('min_pay')) {
$this->db->where('min_pay <', $this->input->get('min_pay'));
}
if($this->input->get('keyword')) {
$this->db->like($this->input->get('keyword'));
}
$query = $this->db->get('table_name');
foreach ($query->result() as $row) {
echo $row->title;
}
To use Search criterias in a nice way you should use Classes and Interfaces.
Let's say for example you define a ICriteria interface. Then you have different subtypes (implementations) of Criteria, TimeCriteria, DateCriteria, listCriteria, TextSearch Criteria, IntRange Criteria, etc.
What your Criteria Interface should provide is some getter and setter for each criteria, you'll have to handle 3 usages for each criteria:
how to show them
how to fill the query with the results
how to save them (in session or database) for later usage
When showing a criteria you will need:
a label
a list of available operators (in, not in, =, >, >=, <, <=, contains, does not contains) -- and each subtypes can decide which part of this list is implemented
an entry zone (a list, a text input, a date input, etc)
Your main code will only handle ICriteria elements, ask them to build themselves, show them, give them user inputs, ask them to be saved or loop on them to add SQL criteria on a sql query based on their current values.
Some of the Criteria implementations will inherits others, some will only have to define the list of operators available, some will extends simple behaviors to add rich UI (let's say that some Date elements should provide a list like 'in the last day', 'in the last week', 'in the last year', 'custom range').
It can be a very good idea to handle the SQL query as an object and not only a string, the way Zend_Db_Select works for example. As each Criteria will add his part on the final query, and some of them could be adding leftJoins or complex query parts.
Search queries can be a pain sometimes, but not as big of a pain as pagination. Luckily, CodeIgniter helps you out a bit with this with their pagination library.
I think you're on the right track. The basic gist, I would say, is:
Grab your GET variables from the URL.
Create your database query (sanitize the GET values).
Generate the results set.
Do pagination.
Now, CodeIgniter destroys the GET variable by default, so make sure you enable http query strings in your config file.
Good luck!
I don't know anything about CodeIgniter, but for the search application I used to support, we had drop-down combo-boxes with category options stored in a database table and would rely on application and database cacheing to avoid round-trips each time the page was displayed (an opportunity for learning in itself ;-). When you update the table of job_type, location, etc. the new values will be displayed in your combo-box.
It depends on
how many categories you intend to have drop-down lists
how often you anticipate having to update the list
how dynamic you need it to be.
And the size of your web-site and overall activity are factors you will have to consider.
I hope this helps.
P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, or give it a + (or -) as a useful answer
A pagination class is a good foundation. Begin by collecting query string variables.
<?php
// ...in Pagination class
$acceptableVars = array('page', 'delete', 'edit', 'sessionId', 'next', 'etc.');
foreach($_GET as $key => $value) {
if(in_array($key, $acceptableVar)) {
$queryStringVars[] = $key . '=' . $value;
}
}
$queryString = '?' . implode('&', $queryStringVars);
$this->nextLink = $_SEVER['filename'] . $queryString;
?>
Duplicate the searchable information into another table. Convert sets of data into columns having two values only like : a search for color=white OR red can become a search on 10 columns in a table each containing one color with value 1 or 0. The results can be grouped after so you get counters for each search filter.
Convert texts to full text searches and use MATCH and many indexes on this search table. Eventually combine text columns into one searchable column. The results of a seach will be IDs which you can then convert into the records with IN() condition in SQL
Agile Toolkit allows to add filters in the following way (just to do a side-by-side comparison with CodeIgniter, perhaps you can take some concepts over):
$g=$this->add('Grid');
$g->addColumn('text','name');
$g->addColumn('text','surname');
$g->setSource('user');
$conditions=array_intersect($_GET, array_flip(
array('keyword','job_type','min_pay'));
$g->dq->where($conditions);
$g->dq is a dynamic query, where() escapes values passed from the $_GET, so it's safe to use. The rest, pagination, column display, connectivity with MVC is up to the framework.
function maybeQuote($v){
return is_numeric($v) ?: "'$v'";
}
function makePair($kv){
+-- 7 lines: $a = explode('=', $kv);
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
}
function makeSql($get_string, $table){
+-- 10 lines: $data = explode('&', $get_string);
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
}
$test = 'lloyd=alive&age=40&weather=hot';
$table = 'foo';
print_r(makeSql($test, $table));

Unserialize values from mySQL

I am using a classified scripts and saves user_meta data in the wp_usermeta table.
The meta_key field is called user_address_info and in it there are all the data like below :
s:204:"a:7:{s:9:"user_add1";s:10:"my address";s:9:"user_add2";N;s:9:"user_city";s:7:"my city";s:10:"user_state";s:8:"my phone";s:12:"user_country";N;s:15:"user_postalcode";s:10:"comp phone";s:10:"user_phone";N;}";
I am not using all the fields on the script but user_add1, user_city, user_state and user_postalcode
I am having trouble to get the data using SQL like the example below (wordpress) :
$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_A);
I would like some help here so that I will display anywhere (I dont mind using any kind of SQL queries) the requested info e.g. the user_city of current author ID (e.g. 25)
I was given the following example but I want something dynamic
<?php
$s = 's:204:"a:7:{s:9:"user_add1";s:10:"my address";s:9:"user_add2";N;s:9:"user_city";s:7:"my city";s:10:"user_state";s:8:"my phone";s:12:"user_country";N;s:15:"user_postalcode";s:10:"comp phone";s:10:"user_phone";N;}"';
$u = unserialize($s);
$u2 = unserialize($u);
foreach ($u2 as $key => $value) {
echo "<br />$key == $value";
}
?>
Thank you very much.
No, you can't use SQL to unserialize.
That's why storing serialized data in a database is a very bad idea
And twice as bad is doing serialize twice.
So, you've got nothing but use the code you've given.
I see not much static in it though.
do you experience any certain problem with it?
Or you just want to fix something but don't know what something to fix? Get rid of serialization then
i have found that the serialize value stored to database is converted to some other way format. Since the serialize data store quotes marks, semicolon, culry bracket, the mysql need to be save on its own, So it automatically putting "backslash()" that comes from gpc_magic_quotes (CMIIW). So if you store a serialize data and you wanted to used it, in the interface you should used html_entity_decode() to make sure you have the actual format read by PHP.
here was my sample:
$ser = $data->serialization; // assume it is the serialization data from database
$arr_ser = unserialize(html_entity_decode($ser));
nb : i've try it and it works and be sure avoid this type to be stored in tables (to risky). this way can solve the json format stored in table too.

Categories