Creating multiple boxes in PHP from MySQL - php

I have made a simple PHP news system that just basically displays information from a MySQL database that I've made, it also uses CSS for a rounded box, but, I also want it to create multiple rounded boxes displaying different news, so, to sum it up, I just want a code that will create a different box for each result.

Inside of your PHP code you will want to put your sql statement within a foreach loop to put each result into their own box.
Here is an easy example:
$dbh = db connection
$result = "SELECT new FROM news;";
$stmt = $dbh->prepare($result);
$stmt->execute();
$newEach = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($newEach as $val){
foreach($val as $key=>$news){
echo '<div class="box">' . $news . '</div>';
}
}
There is probably a better way to get the individual items without having to do a nested foreach but so far I have been unable to find a way that works this well when wanting individual results from a select query.

Related

Is there a way to combine independent functions of a page into single and query once to distribute fetched data individually

First of all, it's an idea, need to share because its solution is not present to me. But if applicable, it can help many PHP developer as well.
I'm developing a WordPress Ad Manager Plugin. Very simple thought, get an image URL into db with an id, and fetch the URL and show them with <img> tag. In my show ad function I did something like this:
<?php
function show_ad($id){
global $wpdb;
$table = $wpdb->prefix . "my_ad";
$query = $wpdb->get_results(
"SELECT *
FROM $table
WHERE id = $id;
");
$output = echo '<img src="'. $query[0]->img_url .'"/>';
return $output;
}
?>
The ad can be shown by any of these ways: PHP Function in Template (<?php show_ad($); ?>), Shortcode, Sidebar Widget. In all the cases the image showing process will be the same function.
Suppose, I have a site, where I added 20 ads into the plugin db. Now I want to show 10 of them into 10 different places, 10 different <div>s. in the same page. So what the function is doing, using the same function in 10 different places means 10 Individual db Queries. And 10 db Queries means 10 times hit to db.
So, I'm seeking a way to combine all the function into one and execute a single db query to fetch data. I'm dreaming something like the following. Assuming there are 10 different ad places in my page:
<?php
// A TOTAL FICTIONOUS CODE BLOCK
if( function_in_this_page_exists( 'show_ad' ) ) {
$function_array = make_them_array_with_vallues();
//so function_array looks like: array( '2','4','1','5','8','10','15', ... )
//execute the combined query function
//and query the db once
$query_result_array = combined_query_function();
//so the $query_result_array looks like: array('2'=>'http://url2.com','4'=>'http://url4.com','1'=>'http://url1.com', ...)
//now, distribute the data to the individual function where they are
//by executing another function that distribute fetched data where their id belongs
distribute_array_data_to_functions($query_result_array);
}
?>
Though it's a fictionous code block, but [if possible], with this way a simple db query can do all the individual queries instead. I don't think such a function-fetching-with-parameter thing is present now in PHP. Any idea?
Firstly, you might use the MySQL keyword IN to fetch more than one id.
Secondly, just write your processing function for the returned data-set as you imagined.
In other words, build the content, insert image URL for each for the ids.
After that, you might think about caching the query and caching the generated content.
$array_with_ids = array('1','2','3');
$sql = 'SELECT *
FROM `table`
WHERE `id` IN (' . implode(',', array_map('intval', $array)) . ')';

Algorithm optimization in PHP app

I'm working on a web application project which displays a list of results to the customer, with pictures, description and some other info. I want to optimize the routine responsible for displaying the results.
Let's say that we have a total of 200 results (products). For each one of them a function is called (let's call it DisplayResults), that fetches some pictures, description, and some other stuff.
DisplayResults currently is within a foreach loop, so as I already mentioned, for each one of the results we have a new function call.
I'd like to ask: how can I optimize this sequence? If I fetch all the info needed to display with a function OUTSIDE the foreach loop (for all the results at once), will I see some difference?
Thank you in advance
EDIT: I'm already using pagination. The data have been already fetched from the database and are stored in an array, so no need for SQL optimization at this point, in my opinion...
EDIT #2: This is how foreach-loop looks like:
foreach ($total['product_data'] as $product_data) {
$tags['$$searchProductList'] .= DisplayResults($product_data);
}
And this is how DisplayResults looks like:
function DisplayResults ($data) {
$tags['$$Description'] = substr($data['description'],0,70)." ...";
$tags['$$FeaturesList'] = getFeatures($data['features']);
$tags['$$PhotosList'] = getPhotos($data['photos']);
$tags['$$Offers'] = getOffers($data['offers']);
.
.
.
.
}
The $data variable contains all the information fetched from the DB for the current result.

Use dropdown list selection as mySQL query parameter

I had asked a similar question a few days ago but think I was trying to do to much at one time. I am hoping someone can help get me started on this.
I have two drop down lists, one will be populated with years (2012, 2011 etc) and I have some mySQL databases called "db_2012", "db_2011" etc. In these databases are tables representing months.
I would like the user to select a year and then use that selection to query the correct db and return a list of table names which will be used to populate the second drop down list. Then click a button "See Results" to query the selected table and show the results.
I am putting this on a wordpress website and am using a php template file that I created. This is still new to me and what I have so far doesnt work like I want it too, it is basically setup now that you select a year and select a month (not populated from db) and click a button. It makes the query and my table is displayed, but I need this solution to be more dynamic and work as described above. Thanks for the help.
echo '<form action="" method="post">';
echo'<select name="years" id="years">';
foreach($yearList as $year){
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select><br />';
echo '<select name="monthList" id="months">';
foreach($monthList as $month) {
echo'<option value="'.$month.'">'.$month.'</option>';
}
echo '</select>';
echo '<input type=\'submit\' value=\'See Results\'>';
echo '</form'>
$yearList and $monthList are just pre populated arrays. So now from here I want to click the See Results button and query my sql database using the parameters from the drop down selections.
$database = $_POST['yearList'];
$month = $_POST['monthList'];
$wpdbtest_otherdb = new wpdb('Username', 'Password', $database, 'localhost');
$qStr = "SELECT * FROM $month";
$myResults = $wpdbtest_otherdb->get_results($qStr, OBJECT);
It sounds like you want to send an AJAX call to a separate php page for security and processing, then have the PHP return XML that you parse back into the second selection box via the AJAX callback. It can be a little messy, but it allows you to check for weird form values that users might inject.
Edit: The PHP will receive your AJAX parameters as parts of the $_GET or the $_POST array. From there, you can do your checks and db call (or not), then add header("Content-Type:text/xml"); so the server sends it back with the correct header. After that you'll need to echo the XML-formatted data you want the JavaScript to receive. Just remember not to echo anything other than the XML if the request is supposed to go through.

Search with PHP/MySQL and dynamically update with jQuery

I was wondering how to do the following best with PHP/MySQL and jQuery:
There is a basic search mask where you enter a city and a from-to-date. You process to the search-result page, where you then can narrow your search results with certain parameters (checkboxes, jQuery slider, text-input, ...). The search-results should then update on the fly without the whole page being reloaded...
I manage to use jQuery ajax and load to send information to another php file, perform e.g. a SELECT and return the results to the search detail page, but I don't know how to combine different changes that narrow the search results.
Furthermore, there are already results on the detail page, so I do not need to add more results but "delete" the results that do not fit anymore...
The thing is that each parameter to narrow the search is connected to another table in the database. Do I have to and how do I add joins to the original query...? Or am I thinking in the wrong direction?
Yes, this is absolutely the right direction. Use
$(document).ready(function() {
$('#ID_OF_YOUR_ELEMENT_TO_LOAD_INTO').load("load.php?parameter1=<?php echo $parameter1; ?>&parameter2=<?php echo $parameter2; ?>");
});
to get the results when the user gets on the page for the first time, to get the results according to your city and your dates.
Check in the load.php which parameters are set and use the ones that are set to build your query. Then, when the form (or forms, depending) are updated, you have to use .load again, like this:
$('#ID_OF_YOUR_FORM_BEING_UPDATED').change(function() {
$('#ID_OF_YOUR_ELEMENT_TO_LOAD_INTO').load("load.php?parameter1=<?php echo $parameter1; ?>&parameter2=<?php echo $parameter2; ?>&parameter3=<?php echo $parameter3; ?>");
});
Get the initial tuples via PHP/MySQL, save them into some Javascript structure and create the html needed to display the data with javascript from this structure.
Any time you want to filter the data you rewrite the html and check the filter condition on the fly, e.g. don't write tuples from the structure that don't match your filter condition.
You can see who this is done at http://www.wowhead.com
This is of course just one way. ;-)
You could always write some code to generate an SQL query based on passed arguments.
You ajax could query the page with a bunch of arguments in addition to your basic city and from-to date based on what the user has selected. If your page preserves the previous search options selected, it should be able to just let the user add on more options and keep processing them in the same way. Your php would then test to see if the arguments are set in the $_POST or $_GET variable ($_POST is more secure for ajax generally, but my example will use $_GET for simplicity) and build the query like that.
Example:
Javascript generates a query like searchAjaxHandler.php?city=Chicago&from=2012-03-01&to=2012-03-05&someColumnLowerRange=500&someColumnUpperRange=700
Your php script then processes as follows:
$query = "SELECT * FROM Data WHERE City=? AND Date > ? AND Date < ?";
$arguments = array($_GET['city'], $_GET['from'], $_GET['to']);
if (isset($_GET['someColumnLowerRange'])) {
$query .= " AND someColumn > ?";
$arguments[] = $_GET['someColumnLowerRange'];
}
if (isset($_GET['someColumnUpperRange'])) {
$query .= " AND someColumn < ?";
$arguments[] = $_GET['someColumnUpperRange'];
}
//execute the query
//using PDOs (google them...they are a good way to prevent sql injection and
//support multiple database types without modifying code too much), create a
//statement with the above query in put the statement in $statement
$statement->execute($arguments); //this uses the $arguments array to fill in the prepared statement's ?'s
//then do the stuff to get the retrieved rows out of the result returned
After all that, the javascript side would just to the same thing you were doing before by replacing all the previous results with the results that you got back.

Display database contents? PHP / MySQL

So I have a chatroom type of database where the text that a user inserts gets stored into a databse as their username in one field and their message in the other. I want to have my page output the database info, so that people can see each others messages.
How do I do this?
Also, is it possible to make a for loop that checks to see if the database has been updated with a new message, therefore it reloads the page? (Then the page outputs the database info again to update everyones messages)
Please help.. i'm so confused.
Take a look at MySQL functions in PHP manual. You need to connect to the server/database and run a select query to get the data from tables.
As for the loop: you could use JavaScript setInterval function and combine that with AJAX call to periodically poll for new records.
Like the others have said, you will want to connect to your database and then query the table that you have the data in.
while($row = mysql_fetch_assoc($results))
{
echo $row['username'] . " said: " . $row['message'] . "<br />";
}
I use mysql_fetch_assoc() instead of mysql_fetch_array() since the arrays are associative arrays (not indexed by integers, but rather by names (associations))
As for displaying the update on the page dynamically, that involves AJAX. Basically what that means is that your page will call out to a background script to get the new records from the database. This would require a new field in your 'messages' table, something like 'msg_delivered' that you could set to '1' when it has been fetched.
You should check out this if you are interested in making an AJAX chat client: http://htmltimes.com/javascript-chat-client-in-jquery.php
To read anything from a mysql database you would use the mysql_connect() and the mysql_query() functions
eg:
$link = mysql_connect('localhost', 'root', '');
$results = mysql_query('select * from messages');
while($row = mysql_fetch_array($results))
{
echo $row['username'] . ': ' . $row['message'].'<br />';
}
To display new messages the best way would be to use AJAX and poll the database from there, either loading a separate page into a DIV or getting XML back and placing into HTML tags. I would recommend using JQuery for these kinds of tasks. Check http://www.sitepoint.com/article/ajax-jquery/ for an example.

Categories