Populate select menu from PHP/MySQL using javascript array - php

I have this code:
<script>
var values = <?php
$sql="SELECT * FROM billing_sagenominalcodes order by code ASC";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$nominalcodes = array();
while($result=mysql_fetch_assoc($rs))
{
$nominalcodes[] = $result['code'];
}
echo json_encode($nominalcodes);
?>;
</script>
<select name="sagenominalcode" id="sagenominalcode">
<script>addOptions(document.getElementById('sagenominalcode'), values);</script>
</select>
it works exactly how i need it to but i am wondering if it is possible to display the column name "name" from the database in the select options as well as the code?
for example rather than just
123
to have it like this
123 - name

You'll want to rigidly separate your php and your js. The way the code is written will work as is, but is very brittle, and can break catastrophically, leading to action-at-a-distance style bugs.
For example, if your database schema were refactored to remove the code column, then your javascript would be rendered broken, with a cause that nobody would suspect.
That said, if you'd like to also display the data in the name column in the select options, you'll have to pass that data into $nominalcodes as well. Right now, it contains an indexed array of data (perhaps an int or a string), but you'll want to change that so it contains an indexed array of arrays.
So, before:
$nominalcodes = array(1,3,5,78,3,2,234);
and after:
$nominalcodes = array(
array(1, 'foobar'),
array(3, 'larry'),
array(5, 'bob'),
...
);
At this point, you'll have to refactor your javascript addOptions function so that it can properly parse an array of arrays, instead of an array of single values.

Related

Parsing through database table and pulling out unique names

I have a table that is listed like this:
Table name: test
|--------------------|
|------Column 1------|
|--------------------|
|John,Raul,Matt,Tyler|
|Tim,Hannah----------|
|Zeke,Brady,Tim,Tyler|
|Elliot,Zeke---------|
|Matt,Andrew,Idda----|
...
And I need to get all of those names into a PHP array, without multiple cases of the same name.
Would I be better off getting each unique name via SQL, or should I just pull the column, and then parse through it via PHP?
The final PHP array would look like:
$test_array[0]="John"
$test_array[1]="Raul"
$test_array[2]="Matt"
$test_array[3]="Tyler"
$test_array[4]="Tim"
$test_array[5]="Hannah"
$test_array[6]="Zeke"
$test_array[7]="Brady"
$test_array[8]="Elliot"
$test_array[9]="Andrew"
$test_array[10]="Idda"
I'm not sure how I would parse each cell in the table. What would you guys do?
I agree it's best to normalize the database. However, given the situation you've described, I would perform the SQL select and use PHP to run through the results.
I'd initialize $results as an empty string:
$results = '';
Then I'd concatenate each row with $results:
$results .= $row;
Then I'd use explode() to put all of the names in an array:
$all_names = explode(',', $results);
Then I'd use array_unique() to reduces the $all_names array to unique values:
$unique_names = array_unique($all_names);
HTH.

Serialized multidimensional stored in MySQLi does not print past first array

Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.

Php array to MySQL query condition structure

I have following array in PHP:
$arr = [1, 3, '4A', '5A', '5C', '2B', '2C', '2E'];
Somehow I need to convert this array to a string which look like this:
$filter = "(id like '1%') OR
(id like '3%') OR
(id like '4A%') OR
(id like '5A%' OR id like '5C%') OR
(id like '2B%' OR id like '2C%' OR id like '2E%')";
The first character of the array value indicates a unique categorie and is wrapped in parentheses.
In the end I will use this to query the database;
$sql = "SELECT * FROM list WHERE {$filter}";
Can someone help me converting this array to the correct string ? What is the best method to achieve this ?
To give you an idea of what I'm trying:
The 'id' column in my database row looks like; 1B2875. Where the first char (1) indicates a categorie and the second char (B) the subcategorie. The given array is a result of a client-side filter request.
You can use regular expressions in SQL:
SELECT * FROM list WHERE id REGEXP '^(1|3|4A|…)[0-9]+$'
The value inside the parentheses can be generated with the PHP function implode('|', $filter_strings)
Note that you should validate and escape the filter strings first to prevent the user input from manipulating the query. The function preg_quote is useful here.

JSON_encode not working with GROUP_CONCAT database selection

I'm breaking my brain on a array from a query in MYSQL that i want to pass to a javascript array.
In the query i select the array with a GROUP CONCAT and the outcome looks like:
1358121600,1,1,0,0,0,0,0,0,1358380800,2,2,0,0,0,0,0,0,1358640000,1,1,0,0,0,0,0,0,1360454400,3,3,0,0,0,0,0,0,1360972800,1,1,0,0,0,0,0,0
But if i use JSON_Encode like this:
<?php echo 'var prijzen = new Array('.json_encode($array_prijzen).');'; ?>
I looks like the array is filled and i can also alert the array, but if i alert prijzen[0] it gives "undefined".
The following code should fix your problem:
<?php echo 'var prijzen = ['.$array_prijzen.'];'; ?>
Building on #datasages 's answer. If $array_prijzen is a genuine php array, then the following will work. I think datasages's answer is based on the fact that your variable named $array_prijzen is actually a string (which seems to be the case). But if it's an array, then do the following (i created a five element array as an example):
<?php $array_prijzen = array(1358121600,1,1,0,0); echo 'var prijzen = ['.implode(",",$array_prijzen).'];'; ?>

PHP MYSQL unserialize() issues

I have a "recruiter" table in my database which has different attributes and one of them is "Professions". "Professions" is a serialized array which I get from a multiple select form. And this works fine.
When I unserialize this attribute nothing is printed - no error, no text.
This is a code I was testing serialization with:
$sql = 'SELECT Company_name, Status, Size, Professions, Seniority_levels, Sector, Website, Location FROM Recruiter';
$query = mysql_query($sql, $con);
while($result = mysql_fetch_array($query, MYSQL_BOTH)){
$recruiters[] = array($result[0], $result[1], $result[2], $result[3], $result[4], $result[5], $result[6], $result[7]);
}
foreach($recruiters AS $recruiter){
$test = unserialize($recruiter[3]);
echo $test[0].'<br>';
}
So basically $test[0] prints nothing although the new lines are printed. Please help!
try printing the $test array and the $recruiters and the $recruiter arrays. See if the result is fine before the unserialisation of the data. If the query returns any data. Also try the while loop with mysql_fetch_assoc. Let me know of the results and if this solves the problem
test = unserialize($recruiter[3]); should become test = unserialize($recruiter[5]); since the sector field is the sixth column .
However what if somewhere in the future you might need to select rows where sectors equal smth ? serialize whont help you then so i suggest you have a look at a different implementation for the sector filed witch is called bitwize http://www.litfuel.net/tutorials/bitwise.htm
Edit
Asuming you hit the right column and the column contains a:1:{i:0;s:27: a:1:{i:0;s:27: a:38:{i:0;s:27: a:9:{i:0;s:39:, it looks like the serialized array is not fully saved in you're db, it's only part of it . So the unserialize function whont return you an array . Have a look at the length of the mysql field i assume you've set it smaller than you need so you're data is trimmed on insert/update .
Edit
a:1:{i:0;s:27: you're still missing the rest of the serialized array . s:27: means a string is following containint 27 characters, and you're serialized array stops there when it should look like
a:1:{i:0;s:27:"123456789012345678901234567";}
( a:1 stands for an array containing 1 value with it's content between {}, i:0; is the array key 0, s:27:""; stands for a string containing 27 characters as the value for the i:0 key ) .

Categories