PHP Make a multidimensional array from one mysql Row's columns? - php

I have the following mysql db row.
id | user_id | title_1|desc_1|link_1|title_2|desc_2|link_2|
and so on up to 10
from this one row I want to remove id and user id and have the resulting multidimensional array.
the main issue is iterarating over the associative array that is returned by my query and splitting it up into arrays of 3.
Array = (
[0] = array (
[tite_1] => 'sometitle'
[desc_1] => 'description'
[link_1] => 'a link'
)
[1] = array (
[tite_2] => 'sometitle'
[desc_2] => 'description'
[link_2] => 'a link'
)
and so on how can I achieve this I am stumped!!?

You probably want to structure your table into two tables like this:
parent(id, user_id, more_fields, whatever_you_need_here)
child(parent_id, title, desc, link)
Now it'll be very easy to get the data that you want to have.
SELECT title, desc, link FROM child WHERE parent_id = 12;
Of course, parent and child should be named appropriately, e.g. user and links.

The correct answer would be to redesign your database to use 3rd normal form. You should probably drop everything and read up on database normalization before you do anything further.
A proper design would be something like:
CREATE TABLE user_has_links (
id INT PRIMARY KEY,
user_id INT,
title TEXT,
description TEXT,
link TEXT
)
To store multiple links per user, you would simply create a new row in this table per link.

The real solution here is to fix your database to normalize these columns into other tables. However, if you are not in a position to fix your database, this code will do the job:
// $output will hold your full result set
$output = array();
while ($row = mysql_fetch_assoc($result)) {
// For each row returned, add a new array to $output
$output[] = array(
// The new array consists of 10 sub-arrays with the correct
// keys and values
array (
"title"=>$row['title1'],
"desc"=>$row['desc1'],
"link"=>$row['link1']
),
array (
"title"=>$row['title2'],
"desc"=>$row['desc2'],
"link"=>$row['link2']
),
...,
...,
array (
"title"=>$row['title10'],
"desc"=>$row['desc10'],
"link"=>$row['link10']
)
);
}

Related

PDO fetch object key value as id and keep the id in the object

I have looked around alot with this problem. I want to get a array of my objects and the id should be the key value. I did this using the PDO::FETCH_UNIQUE.
It almost worked the way I want to. Problem here is that the ID will be removed from the object and will only show as the key value. But I want the key value as the id value AND KEEP the id attached to the object.
I tried this myself
$getUsers->fetchAll(\PDO::FETCH_UNIQUE|\PDO::FETCH_CLASS, User\Basic::class);
This does return the id, but the id is everywhere 0.
concept:
{
id: 3,
name: 'pietje'
},
{
id: 4,
name: 'pietje'
}
Then i want a array of object like this (I think I made a mistake here)
[3 => {
id: 3,
name: 'pietje'
},
4=> {
id: 4,
name: 'pietje'
}]
But like i sayed, the id in the object is always 0the way I did it, and i could not find anything on the internet about the way I want it. Yhea sure I can loop every user and add a id, but then I can just loop through every user and create a new array with the user id as key value.
Any one?
Just select your field twice,
SELECT id, table.* FROM table ...
PDO::FETCH_GROUP will allow you to group results; since you are grouping by id and should be unique you will get all rows as needed.
EDIT:
$sth = $pdo_dbh->prepare('SELECT id, name FROM users');
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
$result = array_map('reset', $result);
will return array like this.
Array
(
[2] => Array
(
[name] => Rob
)
[1] => Array
(
[name] => George
)
)
it helps move ID column as keys in result array, and only keeps desired columns in array values. I fail to notice you wish to fetch results as class object.
Unnecessary nesting removed with array_map.

storing array in a sql database

I started getting into arrays and don't quite get it to work well. I'm used to work with explode/implode functions but I though arrays would make my life easier in this part of the code. Here is the function called:
function save_event($event_items = NULL) {
include 'connect.php';
$now = date("Y-m-d H:i:s");
$sqla = "
INSERT INTO `event`(`event_items`, `event_entered`)
VALUES ('$event_items','$now')";
$resulta = mysqli_query($link, $sqla);
if(!$resulta)
{
echo '<br/>An error occurred while inserting your data. Please try again later.<br/>';
}
else
{ echo 'this is the variable to be stored:<br/>';
print_r($event_items);
$sql = "SELECT * FROM `event` WHERE event_entered = '".$now."'";
$result = mysqli_query($link, $sql);
if($result)
{ while($row = mysqli_fetch_assoc($result))
{ echo '<br/></br>This is the value of the database:<br/>';
print_r ($row['event_items']);
}
}
}
}
This function prints:
this is the variable to be stored:
Array( [0] => Array ( [item] => Powered Speaker [note] => [quantity] => 2 [price] => 200.00 [category] => Audio ) [1] => Array ( [item] => Wireless Microphone [note] => Lavalier [quantity] => 3 [price] => 175.00 [category] => Audio ))
This is the value of the database:
Array
In phpMyAdmin, all I see in the column event_items is the word Array.
Additional info:
I have a table called Groups, each group will have one or multiple orders (another table called Order) and each order will have also one or multiple events (another table). Lastly, each event will have one or multiple items (each item with its corresponding price, quantity, note and category), which are stored in one (or many) columns in the Event table.
Don't try to store an array in one field. You should store each item in the array as it's own row in a related table.
You are trying to insert multiple values in a single database record, this is not impossible but it's also not recommended in general.
The main reason someone would do this would be for optimization, which is not at all something you should worry about for now.
What you really want to do is review your database schema, if you wish to store an array of value, you need to create a new row (record) for each of those. This might necessitate the creation of another table, depending on what you want to do.
You could serialize your array with the serialize() function.
Example:
serialize($event_items);
Generates a storable representation of a value.
This is useful for storing or passing PHP values around without losing
their type and structure.
http://php.net/manual/en/function.serialize.php

php & mysql: most efficient method to check large array against database

I have a large set of data stored in a multi-dimensional array. An example structure is as below:
Array
(
[1] => Array
(
[0] => motomummy.com
[1] => 1921
[2] => 473
)
[4] => Array
(
[0] => kneedraggers.com
[1] => 3051
[2] => 5067
)
)
I also have a table in a mysql database that currently contains ~80K domain names. This list will grow monthly by possibly ~10K+ domain names. The goal is to compare Array[][0] (the domain name) against the mysql database and return an array with preserved values (but key preservation is not important) that only contains unique values.
Please note, that I only want to compare the first index alone, NOT the entire array.
The initial multi-dimensional array is assumed to be enormous in size (more than likely anywhere from 100k to 10 million results). What is the best way to get data back that is not contained in the database?
What I am doing now is simply storing to an array, the complete list of domains from the database, then using the following function, comparing each value in the initial array against the database array. This is horribly slow and inefficient obviously.
// get result of custom comparison function
$clean = array_filter($INITIAL_LIST, function($elem) {
$wordOkay = true;
// check every word in "filter from database" list, store it only if not in list
foreach ($this->domains as $domain) {
if (stripos($elem[0], $domain) !== false) {
$wordOkay = false;
break;
}
}
return $wordOkay;
});
Some pseudo code or even actual code would be very helpful at this point.
Use the DBMS! It was made for stuff like that.
Create a temporary table temp { id (fill with array index); url (filled with url)}
Fill it with your array's data
Ideally create an index on temp.url
Query the database:
SELECT * FROM `temp` LEFT JOIN `urls`
WHERE urls.url = temp.url AND urls.url IS NULL;
(the table urls is your existing data)

PHP Arrays, Serialization and Unserialization

I have a problem. I have a website with people and different transactions they make to and from a fake online bank. I want to be able to store an array of each person's transactions on my mysql database. I want each transaction to be defined as an associative array with a timestamp and the sql query that represents their transaction with the "bank".
Then I want those, after being serialized, to be the values of a transactions array that holds all of their transactions. Then I want to serialize that and store it in the database so that later I can add a transaction by unserializing it and appending a serialized array of another transaction to it. So far this code below works except that it just overwrites the one transaction and doesn't append a new one. I'd really appreciate any help.
Thanks in advance
function modify_transactions($row, $sql)
{
$sql=mysql_real_escape_string($sql);
if(isset($row["TRANSACTIONS"]))
{
$transactions = unserialize($row["TRANSACTIONS"]);
}
else
{
$transactions = array();
}
$transaction_array = array("timestamp"=>time(),"query"=>$sql);
$transaction_data = serialize($transaction_array);
$transactions[] = $transaction_data;
$transactions_upload = serialize($transactions);
$name = $row["NAME"];
$query = "UPDATE band.students SET TRANSACTIONS = '$transactions_upload' WHERE students.NAME = '$name'";
mysql_query($query);
}
If I were you, I'd rather go for a new table where every entry would represent a transaction and that had a foreign key student_id.
That'd be much, much, much cleaner and more flexible and scalable (i.e. what if you want to show the last 3 transactions of user X? What if a user had several million transactions?).
First, you don't need to serialize each array, then serialize again. Serialize is recursive:
$array = array(
array(
'1',
array()
),
array(
'2',
array()
)
);
$serialized = serialize($array);
$unserialized = unserialize($serialized);
echo "<pre>";
print_r($unserialized);
echo "</pre>";
Prints:
Array
(
[0] => Array
(
[0] => 1
[1] => Array
(
)
)
[1] => Array
(
[0] => 2
[1] => Array
(
)
)
)
So just serialize right before inserting into the database.
Second, you should change your database structure. Like vzwick mentioned, create a new table with a foreign key of the student. That way each entry represents a transaction.
Also, why are you storing the actual SQL query? That doesn't make any sense to me. Why don't you actually make a fake transaction?

How to create php array from mysql result, perform calculation, resort array, present results

I have a photo website on which I am trying to perform a query against a MySQL database. The query is against a concatenated field of 'title' and 'keyword' called 'title_keyword'.
I want to take the search results and sort them by a newly formed variable called 'sort_priority' which is checking to see if the search word is in the 'title' field. If it is in the 'title' field then I want to assign a value of 1 and if not in the title field then a value of 2. The resulting array will be sorted by 'sort_priority' and output to the screen.
Here is the logic I am using with PHP and MySQL:
1) Query the MySQL database and assign variables. (This works just fine)
2) Take the results, assign each field to a variable, create a new variable that performs a calculation on one of the variables returned
$data_array=array();
// get each row
while($row = mysql_fetch_array($result))
{
//get data
$image_id = "{$row['image_id']}";
$title = "{$row['title']}";
$imageurl = "{$row['imageurl']}";
// Create sort_priority to identify if search word is in title field.
//If it is then set to 1 to force this higher in the result list after sorting
$sort_priority = 2;
if(stristr($title,$search))
{ $sort_priority = 1;}
Everything above this point works. Now for the part I'm stumped on. How to create and add data to the array and then sort on my new $sort_priority variable.
Here is what I've written but it just doesn't work**
// Create array and sort by title then keyword (tk_sort)
$data_array = array(
'image_id' => $image_id,
'title' => $title,
'imageurl' => $imageurl,
'sort_priority' => $sort_priority);
// Obtain a list of columns
foreach ($data_array as $key => $row) {
$image_id[$key] = $row['image_id'];
$title[$key] = $row['atitle'];
$imageurl[$key] = $row['imageurl'];
$sort_priority[$key] = $row['sort_priority'];
}
// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($sort_priority, SORT_ASC);
// end of array creation and sort
3) Output the newly sorted array to a table
Not sure how to get the data out of it. Do I have to use a loop or something?
You could just let MySQL do the majority of the work. This should work (haven't tried it myself):
SELECT CONCAT_WS('-', `title`, `keyword`) AS search_term,
IF( INSTR(`search_term`, 'your_search_value_here') > 0, 1, 2 ) AS priority_key,
`image_id`, `imageurl`
FROM table_name_here
ORDER BY `priority_key`;
HTH.

Categories