How do I use PHP arrays for my purposes? - php

I'm making a website for a music promotion company. The website contains an individual page for each promoted artist; in which their upcoming events appear. There is also a seperate 'events' page.
I was wondering how to create and use arrays so that I could update any upcoming events in one place and for the information to be echoed out on these two seperate pages.
Also, on the events page all of the artists' events will need to be echoed out in chronological order.
Is this the right way of approaching it?
<?php
$donevents = array();
$donevents[101] = array (
"venue" = "The Moon Club",
"date" = "5th December 2013",
"link" = "www.candyratrecords.com"
);
$donevents[102] = array (
"venue" = "Chapel Arts Centre",
"date" = "8th August 2013",
"link" = "www.chapelarts.co.uk"
);
?>

One Little Character Makes Such A Difference (TM):
$donevents[101] = array (
"venue" => "The Moon Club",
"date" => "5th December 2013",
"link" => "www.candyratrecords.com"
);
Check out the PHP manual on Arrays.
Also, it's very bad design to store events in program code.

If you are not using a database, a CSV file may be a good alternative to keep your data separate from your code. Look into using PHP's functions for reading CSV files into arrays, and you can store your file above the webroot so that it can't be publicly accessed.
Using a CSV file will make it much easier to maintain your data if using an actual database is not an option.

Related

How to insert / store multiple items in a single cell DataBase using PHP & MYSQL

I have a column named - points in a table
I need to insert/store multiple values inside a points column field and display them as list items
EX: points (column):
[100% Wool, Width approx 72cm / 28 inches, Can be used as an area carpet]
output required:
100% Wool
Width approx 72cm / 28 inches
Can be used as an area carpet
My way was to do it with an array, but how?
May I know any other ways to handle it using php & MySQL.
Yes, you can store an array in a single table column. But first you need to convert the array into a string. For examle:
$dataarray = [
'title' => '100% Wool',
'properties' => [
'Width approx 72cm / 28 inches',
'Can be used as an area carpet'
]
]
$datastring = serialize($dataarray); // returns string
// save to to your database, using $datastring as a value for the 'points' column
[...]
After you read the data from your database again, simply un-serialize the stored data and you get the array back:
// load data from database
[...]
$datastring = $row['points'];
$dataarray = unserialize($datastring);
print_r($dataarray);
be aware that there are limits to the amount of data a single mysql-column can store, see https://dev.mysql.com/doc/refman/8.0/en/char.html
as an alternative to serialize() / unserialize(), you may use json_encode() / json_dencode(), which is a bit safer and uses a more universal storage format, see https://www.php.net/manual/en/function.unserialize.php

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.

Storing arrays vs associative tables in MySQL

I have looked in a lot of places and on this site and I am at a development block. I'm making a website and using MySQL to store stuff using PHP. Part of this website is I want to store the types of games a user plays which would be split up into three categories, Game / Platform / Username.
As a coder, I want to make a set of parallel vectors/arrayLists to hold these things, since the amount of games they might play is undefined. I was thinking of making a table but every time I try it doesn't show up in the database. From what I found, people say to not use arrays for databases since that ruins the purpose of a database. How would I store these fields dynamically?
Also from what I found, there is a thing called serialize() which I don't understand exactly how to use it, I can look that up. However, people say that it's not the "proper" way of doing something like this, but they could be wrong.
Serialize takes an array and converts it to a string. You can then take that string and save it a single table entry.
It might go something like this:
$user = array();
$games = array();
$games[] = array("Game" => "Chess", "Platform" => "Computer", "UserName" => "ChessMaster");
$games[] = array("Game" => "Checkers", "Platform" => "Mobile", "UserName" => "CheckersPlayer");
$games[] = array("Game" => "Solitaire", "Platform" => "Computer", "UserName" => "SolitaireUser");
$user[] = $games;
Now in order to save the entry into a database you convert the user array into a string with serialize().
$serializedUser = serialize($user);
Which will output this:
//echo $serializedUser;
a:1:{i:0;a:3:{i:0;a:3:{s:4:"Game";s:5:"Chess";s:8:"Platform";s:8:"Computer";s:8:"UserName";s:11:"ChessMaster";}i:1;a:3:{s:4:"Game";s:8:"Checkers";s:8:"Platform";s:6:"Mobile";s:8:"UserName";s:14:"CheckersPlayer";}i:2;a:3:{s:4:"Game";s:9:"Solitaire";s:8:"Platform";s:8:"Computer";s:8:"UserName";s:13:"SolitaireUser";}}}

Save php function in mysql

It has been my late-childhood dream to create a game, and now as I actually know how I thought I should fulfill my dream and started working on a little game project in my spare time. It's basically a combat type of game where you have up to 3 units, as well as your opponent, and you take turns ( since it's http, you know that feel ) to attack each other and cast spells and stuff. The issue I came across with is with abilities and how to store them. Basically if I were to store abilities in an array it would look something like
$abilities = array(
0 => array(
'name' => 'Fire ball',
'desc' => 'Hurls a fire ball at your enemy, dealing X damage.'
'effect' => function($data){
$data['caster']->damage($data['target'], $data['caster']->magicPower);
}
),
1 => array(...
);
But if I were to store abilities this way, every time I needed to fetch information about a single ability I would need to load the whole array and it's probably going to get pretty big in time, so that would be a tremendous waste of memory. So I jumped to my other option, to save the abilities in a mysql table, however I'm having issues with the effect part. How can I save a function into a mysql field and be able to run it on demand?
Or if you can suggest another way to save the abilities, I may have missed.
To answer your question related to storing arrays into database like MySQL I would like you to serialize the Array as String. The normal direct serialization not going to work because they don't deal with closure.
You need to use classes like super_closure which can serialize the methods and convert them into string. Read more here
https://github.com/jeremeamia/super_closure
$helloWorld = new SerializableClosure(function($data){
$data['caster']->damage($data['target'], $data['caster']->magicPower);
});
$serializedFunc = serialize($helloWorld);
Now you can create array like this:
$abilities = array(
0 => array(
'name' => 'Fire ball',
'desc' => 'Hurls a fire ball at your enemy, dealing X damage.'
'effect' => $serializedFunc
));
This Array can now be saved directly, serialized or encoded to JSON.
I would recommend you to look at Redis or Memcache for caching query results and don't use MySQL to store functions.
You could have tree tables
spell
id
name
description
spell_effect
id
name
serversidescript
spell_effect_binder
spell_id
spell_effect_id
This would make sure, that your logic is in php files, where ever you would like them to be located, but all the meta of the spells, effects and how they bind together in the database. Meaning you will only load the function/script of the ones in need. Plus, giving you the possibility to append multiple effects to one spell.
//Firedamage.php
public function calculateEffects($level,$caster,$target) {
$extraDamage = 5*$level;
$randDamage = rand(10,50);
$caster->damage( $target, ($randDamage+$extraDamage) );
}
Spell_effect entry
id = 1
name = 'firedamage'
serversidescript = 'Firedamage.php'
spell
id = 1
name = 'Fireball'
description = 'Hurls a fireball at your foe'
spell_effect_binder
spell_id = 1
spell_effect_id = 1

Make post archives with pure PHP and yii?

I would need to create archives listing ( much the same functionality as the ones in WP websites ), but with using PHP and Yii framework. Since i've been thinking about how I could accomplish this a lot and didn't come up with anything useful, i'm asking your help here.
So for example, mysql table would look something like this:
Columns:
id (int AI, primary )
title ( varchar )
content ( text )
creation_date ( timestamp )
How could I use the timestamp column value, to select only the posts in distinct months posted ( so that I can determine which months I need to list as links to the respective archive page which will list all the posts posted under that month ) ?
Btw, only helping me on how to do it with PHP is enough, you don't have to go through the hussle of making the code work with Yii since, obviously it is not possible, because you dont have controllers, models etc. :)
Gj to whoever voted down my question, you were realy helpful. I guess haters exist even on these kinds of websites, which is sad. Anyways ,enough about them, here is something I came up with today by learning new MySQL function, which I didn't know existed before :)
You can just use MySQL DATE_FORMAT(date_column,'%format') to select the desired month, year, day, or any other "part" of the date, even though if the date is in unix timestamp. This is a simple code I came up with after a bit of fiddling around.
$query = "SELECT DISTINCT DATE_FORMAT(creation_date,'%M') as creation_month, DATE_FORMAT(creation_date,'%Y') as creation_year FROM posts";
$result = $connection->query($query);
if($result) {
while($row = $result->fetch_assoc()) {
$archiveArray[] = $row;
}
print_r($archiveArray);
echo '<h3>Our Archives by month</h3>';
echo '<ul>';?>
<?php foreach($archiveArray as $archiveRecord) : ?>
<li>
<?php echo $archiveRecord['creation_month'] . ' ' . $archiveRecord['creation_year']; ?>
</li>
<?php endforeach;
echo '</ul>';
}
What this code does is it "reads" the timestamp in the "creation_date" column from the DB, puts it inside the desired "format" which is specified by %M and %Y ( similar to PHP date() function formating) and assigned to immaginary column names on the fly called craetion_month and creation_year. Note the DISTINCT select, since I don't want months to repeat themselves for each post under that particular month. After that we just list them as anchors in an unordered list. This was the main problem, the rest is easy to do :)

Categories