PHP Arrays - Help storing and sorting multiple columns - php

I'm working on a search system for my database where I break the search phrase into individual search words, search my mySQL database keyword table for any occurrence of those words, and then output a list of IDs associate with the keyword.
I want to add those ID's to a new array that will also contain a count value and (from a new query) the name of the place belonging to the ID, resulting in:
array(ID, count, name)
For each search word I want to go through this process and if the ID is already in the above array I want to increase the count value and if not, I want to add it with a count value of 1.
When the array is built and all the counting is done, I want to sort it by count and then name, and then output the results.
I've programmed PHP for quite some time but I've never been good with building and manipulating arrays so any help related to building, searching, editing, and sorting a 3-column array is appreciated.
Here's some code below where I'm just trying to insert data into the array and spit it out, which obviously doesn't work:
<?php
$id = 5;
$count = 1;
$name = "PlaceName1";
$arrayPlaces = array($id, $count, $name);
echo "5: " . $arrayPlaces[5] . "<br />";
?>

<?php
$id = 5;
$count = 1;
$name = "PlaceName1";
$arrayPlaces = array(
$id => array(
'count' => $count,
'name' => $name
)
);
echo "5: " . $arrayPlace[5]['name'] . "<br />";
?>

Related

Select pairs of value from 2 columns from table A and insert it into another table B in random order

I'm developping a quiz app, and for this I use 2 different tables:
One is "question", where there are questions and answers
the other one is "answer_quizz_user" with a unique id depending on the candidate, where I have exactly the same column than "question", with the answer in a random order.
My goal is to show the same question with the same answer in a random order, and to save it in the db like this.
This is what my table looks like
I would like to select the column by pair
(answer"X"_right_answer is a boolen which mean right or wrong answer):
(answer1,answer1_right_answer),
(answer2,answer2_right_answer),
(answer3,answer3_right_answer),
(answer4,answer4_right_answer),
(answer5,answer5_right_answer),
(answer6,answer6_right_answer)
to shuffle it, and insert it in "answer_quizz_user".
I tried different things like :
for ($n=1; $n <=6 ; $n++) {
INSERT INTO answer_quizz_user SELECT
answer".$n." FROM question
WHERE question_question = "q1"
ORDER BY RAND()}
but none worked. I have absolutely no idea how to manage this select->insert. I know that I should have done another table for answers, but now it's too late, the app is almost finish, I just need this random part...
Thanks for your help and sorry for my bad english..
Something like this should work, although your database structure is quite bad. Next time use a separate table for your answers.
It isn't a copy-and-paste solution (I would needed to know more about your code to do that), but I hope it will be enough to set you on the right path.
The basic idea is, you get your pairs from the db, put them in an array, use php's built-in shuffle() function, then insert your rows.
// Gets the required row from database
$query = "select * from question where question_question = 'q1';";
$result = $db->query($query);
if($result->num_rows > 0) {
$question = $result->fetch_assoc();
// Create an array with the pairs
$pairs = array();
for($n = 1; $n <= 6; $n++) {
$pairs[] = array(
'Answer' => $question['answer' . $n],
'IsRight' => $question['answer' . $n . '_right_answer'],
);
}
// Arrange pairs in random order
shuffle($pairs);
// Insert the new rows
foreach($pairs as $pair) {
$query = "insert into answer_quizz_user values ('" . $pair['Answer'] . "', '" . $pair['IsRight'] . "');";
$db->query($query);
}
}
I hope, I could be of any help.

how to fetch and show the results randomly with/without loop php

hello all i am having a site where i need to show random users/ members in this format
i want images of the user in the format as above randomely i have more than 9000 members and need to show the random users in this format the design repeat itself by three
i dont know how to use the loop or use the query to show the images in the above format.
my query is like
$getimages=($con,"select image,id,somethingelse from tablename where id !='' order by rand() limit 21");
// i want 21 images to show here 7*3 (the image here repets it self by three)
while($theimagelink=mysqli_fetch_array($getimages)){
// i think array_push may help but dont know how to implement..
}
please give me some hints or any llink i am stuck over here .....
numbering of the image can be changed ....
i need all the three things of select query to display image
First, you want to get all members, and pull them into an array using your preferred method.
SELECT MemberID,ImageLink,Field4,Etc FROM Members
Then you can randomly select a MemberID by using array_rand():
<?php
$input = array(array('MemberID' => 1, 'ImageLink' => 'someimage.jpg'),array('MemberID' => 2, 'ImageLink' => 'someimage.jpg'),array('MemberID' => 3, 'ImageLink' => 'someimage.jpg'));
$rand_keys = array_rand($input, 2);
var_dump($input[$rand_keys[0]]) . "\n";
var_dump($input[$rand_keys[1]]) . "\n";
?>
Reference: http://php.net/manual/en/function.array-rand.php
To solve your updated question
$getimages=mysqli_query($con,"select image,id,somethingelse from tablename where id !='' order by rand() limit 21");
// i want 21 images to show here 7*3 (the image here repets it self by three)
$Results = array();
while($tmp=mysqli_fetch_assoc($getimages)){
$Results[] = array('image' => $tmp['image'], 'id' => $tmp['id'], 'somethingelse' => $tmp['somethingelse']);
}
var_dump($Results);
Then you can just iterate through the array
for ($i=0; $i < count($Results); $i++) {
echo "<img src='" . $Results[$i]['image'] . "' alt=''><br/>"
echo $Results[$i]['id'] . '<br/>'
echo $Results[$i]['somethingelse'] . '<br/><br/>'
}

Gravity Forms get field entries

A logged in user fills out a form several times. From his entries, I'm attempting to get all of his inputs for a specific field and put them into a PHP array.
For the sake of simplicity, assume the form has ID 10 with the first field called 'SomeField' and the user was logged in (and is still logged in) for all entries.
Here's my best attempt at creating an array of all SomeField entries from the user:
get_currentuserinfo();
$searchCriteria = array(
array(
'key' => 'created_by',
'value' => $current_user->user_login
),
array(
'key' => '1',
'value' => 'SomeField'
),
);
$form = GFAPI::get_entries( 10, $searchCriteria );
echo print_r($form);
Unfortunately, this print_r appears to display an empty array. I believe my searchCriteria is somehow incorrect.
I found it's easier to omit the second parameter ($searchCriteria) and simply use $form[0]['1'] for example which will display the first field of the first entry of the specified form.
I found with user23058230 great solution in the second answer I always got the latest form created, which worked well for new signups but not later on.
Assuming here that the form ID is number 1, you can search it with a for loop using the entry_id which is available in the user's login array as
$current_user->entry_id
No search query is needed other than the form you want returned - in this case form #1.
You can search other items using the keys you can see from your array dump.
Great solution which with the addition of this code solved my problem.
$form = GFAPI::get_entries( 1, '');
$what_i_want = 0;
for( $i = 0; $i < count($form); $i++ ){
if( $form[$i]['id'] == $current_user->entry_id ){
// the item I want
$what_i_want = $form[$i]['22'];
//echo " I " . $form[$i]['id'] . " F " . $form[$i]['22'] . " i " . $i . " T " . $what_i_want . '<br />';
break;
}
}

How can I copy a database table to an array while accounting for skipped IDs?

I previously designed the website I'm working on so that I'd just query the database for the information I needed per-page, but after implementing a feature that required every cell from every table on every page (oh boy), I realized for optimization purposes I should combine it into a single large database query and throw each table into an array, thus cutting down on SQL calls.
The problem comes in where I want this array to include skipped IDs (primary key) in the database. I'll try and avoid having missing rows/IDs of course, but I won't be managing this data and I want the system to be smart enough to account for any problems like this.
My method starts off simple enough:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Two notes:
Yes, I should probably move that $localityMax check to a PHP loop.
I'm intentionally skipping the first array key.
The problem here is that any missed key in the database isn't accounted for, so it ends up outputting like this (sample table):
1 - Tok
2 - Juneau
3 - Anchorage
4 - Nashville
7 - Chattanooga
8 - Memphis
-
-
I want to write "Error" or NULL or something when the row isn't found, then continue on without interrupting things. I've found I can check if $i is less than $row[$i] to see if the row was skipped, but I'm not sure how to correct it at that point.
I can provide more information or a sample database dump if needed. I've just been stuck on this problem for hours and hours, nothing I've tried is working. I would really appreciate your assistance, and general feedback if I'm making any terrible mistakes. Thank you!
Edit: I've solved it! First, iterate through the array to set a NULL value or "Error" message. Then, in the assignations, set $i to $row["id"] right after the mysql_fetch_assoc() call. The full code looks like this:
//Run query
$localityResult = mysql_query("SELECT id,name FROM localities");
$localityMax = mysql_fetch_array(mysql_query("SELECT max(id) FROM localities"));
$localityMax = $localityMax[0];
//Reset
for ($i=1;$i<$localityMax+1;$i++)
{
$localityData["id"][$i] = NULL;
$localityData["name"][$i] = "Error";
}
//Assign table to array
for ($i=1;$i<$localityMax+1;$i++)
{
$row = mysql_fetch_assoc($localityResult);
$i = $row["id"];
$localityData["id"][$i] = $row["id"];
$localityData["name"][$i] = $row["name"];
}
//Output
for ($i=1;$i<$localityMax+1;$i++)
{
echo $i.". ";
echo $localityData["id"][$i]." - ";
echo $localityData["name"][$i];
echo "<br />\n";
}
Thanks for the help all!
Primary keys must be unique in MySQL, so you would get a maximum of one possible blank ID since MySQL would not allow duplicate data to be inserted.
If you were working with a column that is not a primary or unique key, your query would need to be the only thing that would change:
SELECT id, name FROM localities WHERE id != "";
or
SELECT id, name FROM localities WHERE NOT ISNULL(id);
EDIT: Created a new answer based on clarification from OP.
If you have a numeric sequence that you want to keep unbroken, and there may be missing rows from the database table, you can use the following (simple) code to give you what you need. Using the same method, your $i = ... could actually be set to the first ID in the sequence from the DB if you don't want to start at ID: 1.
$result = mysql_query('SELECT id, name FROM localities ORDER BY id');
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[(int) $row['id']] = array(
'id' => $row['id'],
'name' => $row['name'],
);
}
// This saves a query to the database and a second for loop.
end($data); // move the internal pointer to the end of the array
$max = key($data); // fetch the key of the item the internal pointer is set to
for ($i = 1; $i < $max + 1; $i++) {
if (!isset($data[$i])) {
$data[$i] = array(
'id' => NULL,
'name' => 'Erorr: Missing',
);
}
echo "$i. {$data[$id]['id']} - {$data[$id]['name']}<br />\n";
}
After you've gotten your $localityResult, you could put all of the id's in an array, then before you echo $localityDataStuff, check to see
if(in_array($i, $your_locality_id_array)) {
// do your echoing
} else {
// echo your not found message
}
To make $your_locality_id_array:
$locality_id_array = array();
foreach($localityResult as $locality) {
$locality_id_array[] = $locality['id'];
}

Database data in PHP array

I have a table in phpmyadmin that stores an 'id' (auto inc), 'title' and a 'date'.
I have a webpage where I display the 10 latest items (I simply order by ID).
On that page I print the title and the date. My wish is to also display the number of the posted item, so the first posted item is 1, the second is 2, etc. I cannot simply print the ID from the database because if I delete a row, the numbers aren't straight anymore.
My idea was to put all the data in an array but I have no clue what the best way to do this is and how I could print that item number. So for example when I want to display the 54th item I can easily print $items[54][id] or something and it will show me the number 54 and to display the title I print $items[54][title].
I don't know if there are simpler methods, plus arrays always start at 0, but my items must start at 1.
Besides this page that shows the 10 latest items, there is another page where it gets the title of the item out of the URL. How will I be able to search the title in the array and display the data the same way but only for that requested title?
Thanks in advance!
"SELECT COUNT(id) as cnt FROM mytable";
you can select the count of all database entries.
and then assign it to your iterator
$i = $row['cnt']; // this will hold the ammount of records e.g. 21
// other query
while($row = mysql_fetch_assoc($result)) {
echo $i;
$i--; // this will decrement on every iteration 21, 20 , 19, and so on.
}
First off. I would add a timestamp field to the database and order by that instead as it feels overall more reliable and gives you additional details which may prove handy later.
To create the multidimensional array I would do something like:
$result = mysql_query(...);
$items = array();
while($item = mysql_fetch_assoc($result)) {
$items[] = $item;
}
Now $items[12] for example would give you item number 13 (since it's 0-indexed).
Lastly, to select only the item with a specific title I would use a query which included a WHERE clause, like
"SELECT ... FROM ... WHERE title = '".$title."'"
It's very important to sanitize this variable before using it in the query though.
You can read more about MySQL on a lot of places. A quick googling gave me this: http://www.tutorialspoint.com/mysql/index.htm
You should learn PHP before starting to program in PHP ;) Read and work through the PHP manual and some tutorials!
As to your question it is a simple loop you want to do. One way of doing it as an example.
Fetch the 10 last items from the database in any way you like, following some code, partly pseudo-code.
$markup = '';
for ($i=1; $i<=count($items); $i++)
{
$markup .= 'Item ' . $i . ': ' . $items['date'] . ' - ' . $items['title'];
$markup .= 'read more';
$markup .= PHP_EOL;
}
echo $markup;
I don't know how you print out your data exactly, but I assume there is a loop in there. Simply set a counter that increments by one at every row and print its value.
As for the title search, you'll have to run another query with a WHERE title = '$title' condition, but beware of SQL injection.

Categories