Fetch dynamic content based on wildcard subdomain - php

I am trying to pull dynamic content from a database based on the wildcard subdomain.
Please see the code below.
<?php
$data = $_GET['get'];
$data = addslashes(str_replace('-',' ',$data));
$town_result = $database->getData("select * from nationwide where town = '$data' ");
if( is_object( $town_result ) )
{
$area = $town_result->fetch_assoc();
}
else
{
$region_result = $database->getData("select * from nationwide where region = '$data' ");
if( !is_object( $region_result ) ) {
header('Location: http://example.com');
}
$area = $region_result->fetch_assoc();
$area['town'] = $area['region'];
}
?>
I have tried changing = '$data' "); to LIKE '%" . $data . "%'"); but this only pulls the first row in my database.

You can review how to use fetch_assoc to get associative records.
https://www.php.net/manual/en/mysqli-result.fetch-assoc.php
You can print $area, then you can verify either array count is 1 or more than 1.
Or best way, you can print sql query and run directly in your db.

Related

Grouping Mysql PHP Query Results

I have a basic PHP page which searches a MySQL Database of retro ZX Spectrum magazine articles.
The address is [www.retroresource.co.uk][1]
The PHP Results Page is fine, in that it produced the results, but I would like to be able to group the results by 'fgames.fgname'
So for example if I searched for Dizzy
Dizzy (as a header)
Table with rows that have fgames.fgname = Dizzy
Spindizzy (as a header)
Table with rows that have fgames.fgname = Spindizzy
Treasure Island Dizzy (as a header)
Table with rows that have fgames.fgname = Treasure Island Dizzy
etc etc
I have googled and looked in a few of my text books, but am unable to see a solution. Any help much appreciated.
Peter
Amended Code after assistance (No results though)
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
require( '../connect_db.php' ) ;
$query = $_GET['query'];
$min_length = 4;
// you can set minimum length of the query if you want
$query = strip_tags($query);
$query = mysqli_real_escape_string ($dbc,$query);
$q = "SELECT fgames.fgname, fgames.fgprorg, fgames.fgprbud, fgames.fgratng, fgames.fgprdsk, ftypes.fttname, frefs.fryymm, frefs.frpage, frefs.frissue, fmagzne.fmname, frefcde.ffname
FROM fgames, ftypes,frefs, fmagzne,frefcde
WHERE ftypes.fttype = fgames.fgtype
and fgames.fglink = frefs.frlink2
and frefs.frentry = frefcde.ffentry
and frefs.frmag = fmagzne.fmmag
and fgames.fgname LIKE '%".$query."%'
order by fgames.fgname ASC" ;
$r = mysqli_query( $dbc , $q ) ;
$current_group = '';
while ( $row = mysqli_fetch_array( $r , MYSQLI_ASSOC ) )
{
if($row['fgames.fgname']) !== $current_group)
{
if($current_group !== '')
{
echo '</table>';
}
$current_group = $row['fgames.fgname'];
echo '<table><tr><th>FGNAME</th><th>FGPRORG</th><th>FGRBUD</th><th>FGRATNG</th><th>FGRDSK</th>
<th>FTTTNAME</th><th>FRYYMM</th><th>FRPAGE</th><th>FRISSUE</th><th>FMNAME</th><th>FFNAME</th></tr>';
}
echo '<tr><td>'.$row['fgname'].'</td><td>'.$row['fgprorg'].'</td><td> '.$row['fgprbud'].' </td><td>'.$row['fgratng'].' </td> <td>'.$row['fgprdsk'].' </td><td>'.$row['fttname'].'</td><td> '.$row['fryymm'].'</td><td> '.$row['frpage'].'</td><td> '.$row['frissue'].' </td> <td>'.$row['fmname'].' </td><td>'.$row['ffname'].'</td></tr>';
}
echo '</table>';
else
{
echo '<p>' . mysqli_error( $dbc ) . '</p>' ;
}
# Close the connection.
mysqli_close( $dbc ) ;
?>
There are two basic approaches.
Either load the query data into a two dimensional array and output with nested loop like this:
$array_for_output = array();
while($row = /* your query fetch mechanism here */) {
$array_for_output[$row['field_you_are_grouping_on']] = $row;
}
foreach($array_for_output as $table_name => $table_data) {
// output table header here
foreach($table_data as $table_row) {
// output individual row
}
// output table closure here
}
Or the other approach is to query using an ORDER BY clause on the field you are trying to group by and detect changes in the current group in single loop
$query = "
SELECT ...
FROM ...
WHERE ...
ORDER BY field_you_are_grouping_on, any_secondary_ordering_field_here ASC";
// execute query here
$current_group = '';
while ($row = /* your query fetch mechanism here */) {
if($row['field_you_are_grouping_on']) !== $current_group) {
// we have started a new group
if($current_group !== '') {
// this is not first table
// so output closure to previous table here
}
$current_group = $row['field_you_are_grouping_on'];
// output new table header here
}
// output row data here
}
// output closure to final table here
The second approach is usually preferable from a memory management standpoint (you don't have to store entire result set in memory at any point), but some beginning developers may not find this not as intuitive as the first method. The first method also may be more appropriate if you want to take the full result set and inject it into some sort of template that is used to render the display.

Adding array into mysql varchat row with comma after creating the array

I have a huge table with some items. I want to retrive specific items from that table according with the players level of gaming . After the code extracts all the specific items i want to add them into an array ( in this case "$cart") . I want to update a mysql row into a varchar field the array separated by a comma ",";
I tried different methods of adding them into the database but something isn't working.
Heres my code :
$sql = mysql_query("select * from iteme where tip != 'Minereu' AND tip != 'Reteta' AND tip != 'Cooking' AND tip != 'Altele' AND tip != 'Potiuni' AND tip != 'Fragment' AND tip != 'Tools' AND tip != 'Medicina' ");
$numaratoare = 0;
$cart = array();
$nivel_player = mysql_query("select * from membri where id !=0 ");
while($informatie_player = mysql_fetch_array($nivel_player))
{
$nivel_actual_player = lvl($informatie_player['experienta']);
$shop_arme_plus_5 = $nivel_actual_player + 5 ;
if ($nivel_actual_player - 5 == 0 )
$shop_arme_minus_5 = $nivel_actual_player - 5 ;
else
$shop_arme_minus_5 = 0 ;
$shop_arme = mysql_query("select * from iteme where tip = 'Arme' AND level_minim < ".$shop_arme_plus_5." AND level_minim > ".$shop_arme_minus_5." AND vandabil = 1 ");
while($informatie = mysql_fetch_array($shop_arme)) {
$numaratoare ++;
//echo " ".$informatie['nume_ro']." , ";
array_push($cart, $informatie['obiect']);
}
mysql_query("INSERT INTO membri_shop_iteme set iteme_arme = ".$informatie["obiect"]." where id_jucator = ".$informatie_player['id']." "); // Here is the problem.
}
Where's the problem? I tried adding implode(', ', $cart); but still i can't add them into database.
Thanks for helping.
may be its string problem $informatie["obiect"] to $informatie['obiect']
mysql_query("INSERT INTO membri_shop_iteme set iteme_arme = ".$informatie['obiect']." where id_jucator = ".$informatie_player['id']." "); // Here is the problem.
to
$newObject=join(",",$cart);
mysql_query("UPDATE membri_shop_iteme SET iteme_arme = '".$newObject."' where id_jucator = ".$informatie_player['id']." "); // Here is the problem.
You use $informatie["obiect"] in your query, but you have to use $cart.
while($informatie = mysql_fetch_array($shop_arme)) {
$numaratoare ++;
array_push($cart, $informatie['obiect']);
}
mysql_query("UPDATE membri_shop_iteme
SET iteme_arme = '".implode("','", $cart)."'
WHERE id_jucator = '".$informatie_player['id']."'");

Using two or more SQL query statements in a PHP loop

$query_country = "select abbr,full_name from Country";
$result_country = $db->query($query_country);//this is the first SQL
foreach ( $result_country as $row ){
echo '<optgroup label="' . $row['full_name'] . '">';
$abbr = $row['abbr'];
$query_airport = "select location from Airport where country_abbr = $abbr ";
$result_airport = $db_other->query($query_airport);//this is the second SQL
foreach ( $result_airport as $row_prime ){
echo '<option>'.$row_prime['location'].'</option>';
}
echo '</optgroup>';
}
As shown above, the 2nd SQL doesn't work.
I tried to NEW a PDO variable( $db_other ) in the 'config.php' file, but it still doesn't work.
My question is that how I can use the second SQL in a PHP loop.
The reason why I want to do this is that I need to make a selection table group by the 'Country name'.
try to quote your query variable and also use db object $db to run query
$query_airport = "select location from Airport where country_abbr = '$abbr' ";
$result_airport = $db->query($query_airport);
Also check $abbr have value so code looks like:-
if(!empty($abbr)) {
$query_airport = "select location from Airport where country_abbr = '$abbr' ";
$result_airport = $db->query($query_airport);
foreach ( $result_airport as $row_prime ){
echo '<option>'.$row_prime['location'].'</option>';
}
}

Add a line through buttons with php, using SQL

I have a database "test" the rows are username, category and testnr.
I want to use php to cross out any buttons/links on my website that user A has already done. For example username: userA finished testnr:1, so the link test1 in category A gets a line through. The following is as far as I got- (I am sorry, I am a beginner).
However, it would be terribly inefficient. I would have to "if" call for every category and, more annoyingly, testnr in each category. I also would need a next $text everytime, since otherwise every button would be crossed off.
There has to be a better way to do it, but I can not think of anything.
$curuser = $membersite->UserName();
$con = mysqli_connect("$host", "$username", "$password","$db_name");
$sql = "SELECT * FROM test WHERE user='$curuser'";
$text = "";
if ( !mysqli_query( $con,$sql ) ) {
die('Error: ' . mysqli_error($con));
}
$results = mysqli_query( $con, $sql );
while( $row = mysqli_fetch_array( $results ) ) {
$category = $row['category'];
$tnr = $row['testnr'];
if( $category = "Categname" && $tnr = 1 ) {
$text="style='text-decoration:line-through'";
}
}
mysqli_close( $con );
Problem is in your if case!!!
change this
if( $category = "Categname" && $tnr = 1 ) {
to
if( $category == "Categname" && $tnr == 1 ) {
You are assigning the values instead of checking!!! thats why all the links get line-through. See this ref

Trying to set up a A-Z filter

Im trying to set a A-Z filter for a table database in PHP. Below I have provided the code I have been working with. In between the bars is the code that I am trying to use. For some reason its saying I need to select a database and I thought I did that. Please any help would be appreciated.
Please and Thank You
/**
* This function displays a grid of cloud computing companies
*/
function cloud_computing_data_grid_display($arg){
// Definitely should have just used views here. Opted to do it live, because
// I didn't want to create more useless nodes to store cloud
// computing details. Really should have just made a "cloud computing dossier"
// content type or something. At least this executes (comparitively) fast...
$form_state = array('method' => 'get');
$filters = drupal_build_form('cloud_computing_data_grid_display_filters', $form_state);
// get companies ------------use this to filter company names and apply A-Z Filter----------
$companies = array(); // array of company names for filtering
$qry = db_select('cloud_computing_capability_data', 'cd');
$qry -> fields('cd', cloud_computing_data_company::db_fields());
// add service provider filter
if (!empty($form_state['values']['service_provider'])){
if (strtolower($form_state['values']['service_provider']) != 'any'){
$provider_plain = check_plain($form_state['values']['service_provider']);
$provider_wildcards = preg_replace('/-/','%',strtolower($provider_plain));
$provider_wildcards = '%' . $provider_wildcards . '%';
$qry -> condition('cd.service_provider', $provider_wildcards, 'LIKE');
}
}
// add service provider filter
if (!empty($form_state['values']['contract'])){
if (strtolower($form_state['values']['contract']) != 'any'){
$contract_plain = check_plain($form_state['values']['contract']);
$contract_wildcards = preg_replace('/-/','%',strtolower($contract_plain));
$contract_wildcards = '%' . $contract_wildcards . '%';
$qry -> condition('cd.contract', $contract_wildcards, 'LIKE');
}
}
// filter by services offered
$iaas_required = $form_state['values']['services']['iaas'];
$paas_required = $form_state['values']['services']['paas'];
$saas_required = $form_state['values']['services']['saas'];
$eaas_required = $form_state['values']['services']['eaas'];
if ($iaas_required){ $qry -> condition('cd.iaas', true); }
if ($paas_required){ $qry -> condition('cd.paas', true); }
if ($saas_required){ $qry -> condition('cd.saas', true); }
if ($eaas_required){ $qry -> condition('cd.eaas', true); }
$qry -> orderBy('cd.company', 'ASC');
$company_rows = $qry -> execute();
foreach ($company_rows as $row){
$company = cloud_computing_data_company::build($row);
$companies[$company -> name] = $company->to_array();
}
$companies_themed = array();
foreach($companies as $name => $company){
$company['services_display'] = array();
$company['services_display']['IaaS'] = cloud_computing_data_wrap_service($company['iaas'], 'IaaS');
$company['services_display']['PaaS'] = cloud_computing_data_wrap_service($company['paas'], 'PaaS');
$company['services_display']['SaaS'] = cloud_computing_data_wrap_service($company['saas'], 'SaaS');
$company['services_display']['EaaS'] = cloud_computing_data_wrap_service($company['eaas'], 'EaaS');
$companies_themed[] = theme('cloud_computing_item', array('company' => $company));
}
$res_path = drupal_get_path('module', 'cloud_computing_data');
drupal_add_css($res_path . '/theme/cloud-computing.css');
drupal_add_js($res_path . '/theme/cloud-computing-grid.js');
return theme('cloud_computing_page', array('companies' => $companies_themed));
}
//----------------------------------------------------------------------------------
// filter by company name
/* Get the letter user clicked on and assign it a variable called $sort */
$sort = $_REQUEST['letter'];
/* Let's check if variable $sort is empty. If it is we will create a query to display all customers alphabetically ordered by last name. */
if($sort == ""){
$qry= "SELECT * FROM cloud_computing_capability_data ORDER BY companies ASC " ;
}else{
/* if varible $sort is not empty we will create a query that sorts out the customers by their last name, and order the selected records ascendingly. */
$qry = "SELECT * FROM cloud_computing_capability_data WHERE companies LIKE '$sort%' ORDER BY companies ASC" ;
}
/* Notice the use of '%' wilde card in the above query "LIKE '$sort%'". */
//next step is to execute the query.
$execute = mysql_query($qry) or die(mysql_error());
/* Before we display results let's create our alphabetical navigation. The easiest way to create the navigation is to use character codes and run them through the "for" loop. */
echo "<p>" ;
for ($i = 65; $i < 91; $i++) {
printf('%s | ',
$PHP_SELF, chr($i), chr($i));
}
echo "</p>" ;
/* now we are ready to display the results. Since out cloud_computing_capability_data table has only three fileds we will display the results in a paragraphs. In the real world you may need to display the results in a table.
To display the results we will use "do while" loop to fetch the results. If no customers are found we will display an error message. */
if(mysql_num_rows($execute)>0){
do{
echo "<p>" .$result['companies']. "</p>" ;
}while($result = mysql_fetch_assoc($execute));
}else{
echo "<p>No customer found.</p>" ;
}
//-----------------------------------------------------------------------------------
Unless db_select is a custom function the function to call is *select_db*. Also I did not see a connection created but I assume that was done earlier.

Categories