Basically I have coded a PHP script to pull information from a JSON file and store it all in one column inside of my MySQL database, here is the format upon which I am storing the data.
(37.50!03:37:42pm PST)
So i basically have multiple entries of similar results stored inside brackets inside of one column.
Now i want limit the results displayed when i pull that information back from the database and display it on my webpage and i cant figure out how? Is there a simple way?
I have tried using LIMIT in my SQL statement but to my understanding(maybe i am wrong) that is used for limiting the number of rows returned and not used for one unique column.
Thank you for your time.
Honestly, it might be easier to accomplish this using PHP. You haven't posted the details of what the multiple data looks like but guessing it is something like this '(37.50!03:37:42pm PST),(37.50!03:37:42pm PST),(37.50!03:37:42pm PST)'.
When fetching the data you split the data and turn it into an array and with preg_split you can have it only return you a limited number of the split array (in the example it uses 50). Post a comment if this doesn't work or if you are able to clarify the format of what multiple entries looks like in the field.
Example:
$rs = mysqli_query($conn, "SELECT yourColumn FROM your_table order by write_here_your_dec_name desc, your_desc_name");
while ($row=mysqli_fetch_assoc($rs)) {
$parts = preg_split('~,~', $row['yourColumn'], 50, PREG_SPLIT_NO_EMPTY);
foreach ($parts as $part ) {
echo "$part<br>";
}
}
Related
In my system, I have plenty of instances of code like the following:
$value = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(price) as total from items WHERE a=1 AND b=2"));
Then $value is used later in the code and has the total price calculated from the array
I'm trying to replicate this in a new piece of code as follows:
$recent_sale_id = mysqli_fetch_array(mysqli_query($con, "SELECT id as id FROM items where item_code='$item_code' and status='BULK-ITEM-SALE' order by sold_at DESC LIMIT 1"));
The query works when run directly against the database (of course replacing $item_code with the item code). But $recent_sale_id then just has the value 'Array'.
I'm wondering two things:
What am I doing wrong? My code seems to be exactly the same as the other code that works correctly.
Is there a simpler way to get a value from a query into a field, without using a function that seems like it will create an array? Is there a more suitable mysqli_fetch* function?
There's no way you could access $value as a number because it is also an array. In the first case you would need to use either $value[0] or $value['total'] to get the result; in the second either $recent_sale_id[0] or $recent_sale_id['id']. You can use either form because mysqli_fetch_array by default returns arrays indexed both by column number and column name.
Unfortunately the MySQLi interface does not have an equivalent to PDO's fetchColumn which allows you to directly fetch the value of a single column from a row in a result set.
If $recent_sale_id is returning a array in this case, that means it is of array type and in terms of getting data from mysql query often it comes in array format though you have added a limit 1.
One thing you can do to get the value is try $recent_sale_id[0] for the actual output.
I have a database in which i've got a table where im having question to be displayed randomly on the main site (about 80 for now). Im reading all the IDs from the database and then randomly selecting one and doing next query to get all the rest needed data of this one. And im curious if should i leave this like that or would it be bether to store all the IDs in .json file and just update it every time i add a question. What is bether? Thanks for help.
If you're just interested in a random record from the table, just do it like this:
SELECT * FROM your_table
ORDER BY RAND()
LIMIT 1;
All in one query and you don't have to retrieve a list of IDs first.
And it's almost always a bad idea to maintain two separate data sources.
I wrote a website using Google App Engine intended for the 'Datastore' database but now the website is already complete and because of Google's resources limit the website goes down too frequently (and I don't have any money to spend on it, even if I did I wouldn't :/)
Question:
When ever I fetch a table, I want to simply return it like this:
Each row is in it's own array to make it easy to iterate through
Instead of the standard number, each key would be the name of column is from
Problem:
No matter if I use fetch_all, fetch_assoc, or fetch_objectI never get anything that looks like what I am trying to get.
I am pretty bad with iterations and for loops so I couldn't figure how to do it manually.
The simplest way to build an associative array of database rows with mysqli_* is to do this:
$mysqli_query = mysqli_query($db_link, "SELECT * FROM tablename");
$result = array();
while($result[] = $mysqli_query->mysqli_fetch_assoc());
and $result will hold the array you want
I am hoping someone can help me because I am attempting to do something that is beyond my limits, I don't even know if a function exists for this within PHP or MySQL so my search on google hasn't been very productive.
I am using PHPWord with my PHP/MySql Project, the intention is that I want to create a word document based on a template.
I have used this guide which is also on stack exchange.
However this approach requires that the number of rows and the values are hard coded, i.e. in his example he has used cloneRow('first_name', 3), which then clones the table to have 3 rows, and then goes on to manually define the tags, i.e.
$doc->setValue('first_name#1', 'Jeroen');
$doc->setValue('last_name#1', 'Moors');
$doc->setValue('first_name#2', 'John');
I am trying to make this dynamic, in my instance I am trying to make a timetable, and one of the child tables is exactly that, so the query I have looks up how many entries there are and then collects a count of them, this $count is then used to dynamically create the correct number of rows. This is the count I am using:
$rs10 = CustomQuery("select count(*) as count FROM auditplanevents where AuditModuleFk='" . $result["AuditModulePk"]."'");
$data10 = db_fetch_array($rs10);
$Count = $data10["count"];
I then use this $document->cloneRow('date', $Count); to executive the clonerow function, which works great and my document now looks something like this.
So, so far so good.
What I now want is for a way to then append each row value of the query into the document, so rather than manually setting the tag value i.e. $doc->setValue('first_name#1', 'Jeroen'); I could use something like $doc->setValue('first_name#1', '$name from row 1'); I suspect this will involve a foreach query but not too sure.
I hope the above makes sense, but please feel free to ask me for anything else and become my personal hero. Thanks
Update: Just for sake of clarity, what I would like is for the output to look something like this:
In my example are 5 results and therefore 5 rows created, I want to set values in following way:
${$date1} = date column from query 1st row
${$date2} = date column from query 2nd row
${$date3} = date column from query 3rd row
${$date4} = date column from query 4th row
${$date5} = date column from query 5th row
I was able to sort this out by inserting the records from the query into a temp table, with an AI ID, then using:
//update timetable with events from temp table
$rs14 = CustomQuery("select * FROM tempauditplan where AuditModuleFk='" . $result["AuditModulePk"]."'");
while ($data14 = db_fetch_array($rs14))
{
$document->setValue('date#'.$data14["rowid"], date('d/m/y', strtotime($data14["date"])));
$document->setValue('time#'.$data14["rowid"], date('H:i', strtotime($data14["time"])));
$document->setValue('auditor#'.$data14["rowid"], $data14["auditor"]);
$document->setValue('area#'.$data14["rowid"], $data14["area"]);
$document->setValue('notes#'.$data14["rowid"], $data14["notes"]);
$document->setValue('contact#'.$data14["rowid"], $data14["contact"]);
}
The trick is to also have a function that truncates the table after use so can be used over again
Might not be the most efficient way, but it works!
I have a table in MySql with several different fields, one of them contains a description that could be a couple of paragraphs long.
I am trying to figure out a way to have php automatically go through these description fields and create a list of the top keywords used. I am looking for the top keywords for the entire table, not each post individually.
I know this is a bit of a resource heavy operation, and it wouldn't be run very often anyways.
But I'd like to get a list like this:
some x 121
most x 110
frequent x 90
words x 50
So that I could see what the top used words are in the description field. Any idea at all where to start?
You can run you query,
loop through the records and append descriptions together into 1 big happy string.
Then, you can explode by ' ' into array
Get array of values using array_count_values()
Re-sort in descending order arsort()
Update
Sample code too:
$string = '';
foreach (your_result_set as one_row)
{
$string .= $one_row['text'];
}
$data = explode(' ', $string);
$data = array_count_values($data);
arsort($data);
If you have control over the database one way would be to add triggers to this table that maintains another table with all keywords.
The insert trigger would go through new.description and increment all keywords found
The delete trigger would do the same but for old.description and decrement the keywords
The update trigger would do the same as delete and insert, ie decrease all found in old.description and increase for new.description.
Once you have done and tried these triggers dump all data and re import it to have the trigger do the work on all existing data.
there are a few ways you can do this. i'm guessing you dont want to count every word, as words like and,if,it etc will all be meaningless.
also how many rows are we talking?
a simple solution is to create and array called words. loop through each row.
explode the paragraph using " ", which gives you each word. you may also wish to do a str_to_lower first if case is an issue.
loop through and use array_key_exists to see if there is a key if not create it.
and add a value of one. otherwise incriment the value by one.
this will give you counts of each word.
if this is for a search of a large database it would be worthwhile adding keywords to a seperate table on insert.
one way i think this would be good is to add the 5 most frequent used words excluding those in the exclude list (and,it,or,a,i etc). and add any word that appears in the keyword table.
there are issues with this. i have this response and dont mention php, sql or query which are what the post related to .maybe it would be worth having tags/keywords added on insert.