Referencing section of php code - php

I have the following PHP code on my site which basically accesses a PHP script that pulls out information from a mysql table;
<?php include('event_connect.php'); ?>
Is it possible to include a reference to a specific section of code in this script?
Basically I have to create 39 different scripts for individual dropdown e.g. in the "XXX" drop down, only records with an identifier "xxx" will show up.
What i thought would be easier than createing 39 scripts is (if possible) just add some sort of reference value to the above code depending on where in the page it is placed. Kind of like how VBA allows you to call a selected function from another...
Edit: This is the PHP i use to access the mysql database, with the code provided by niet added in - works a treat! Thank you.
<?php
//Get te CSS styling
// Make a MySQL Connection
mysql_connect("xxxx", "xxxx", "xxxx", "xxxx") or
die(mysql_error());
mysql_select_db("xxxx") or die(mysql_error());
// Retrieve all the data from the "xxxx" table
switch($section) {
case 1:
$result = mysql_query("SELECT * FROM `Events_List` WHERE `Value` = 'value_1' LIMIT 0 , 30") or die(mysql_error());
break;
case 2:
$result = mysql_query("SELECT * FROM `Events_List` WHERE `Value` = 'value_2' LIMIT 0 , 30") or die(mysql_error());
break;
// store the records of the "xxxx" table into $row array and loop through
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $name = $row['name'];
$Event = $row['Event'];
$Date = $row['Date'];
$Type = $row['Type'];
$Description = $row['Description'];
$Event = htmlspecialchars($row['Event'],ENT_QUOTES);
$Date = htmlspecialchars($row['Date'],ENT_QUOTES);
$Type = htmlspecialchars($row['Type'],ENT_QUOTES);
$Description = htmlspecialchars($row['Description'],ENT_QUOTES);
echo " <div id='ev_con'>
<div id='ev_img'> </div>
<div id='Event'> $Event </div>
<div id='Date'> $Date </div>
<div id='Type'> $Type </div>
<div id='Description'> $Description </div>
</div>";}
?>
This runs one query fine, but having trouble getting multiple queries running..

Maybe something like this?
$section = 1;
include("event_connect.php");
And in your event_connect file:
switch($section) {
case 1:
// do things
break;
case 2:
// do other things
break;
// ...
}

how about...
function get_event_connect($eventID){
switch($eventID){
case "1" :
// output code
break;
case "2" :
//output code
break;
}
}
$eventID = "1";
echo get_event_connect($eventID);

Related

how do i add a page indicator like "Question 1 of 10"?

How can i add something like this to my quizzer page indicator I've been searching and trying for a couple of days i couldn't figure this out.
total question
<?php
//total question
$db = new db;
$link = $db->dbconnect();
$iauid = $_SESSION["uid"];
$qizid = $_SESSION["qizid"];
$qry = "SELECT COUNT qcatid FROM AS total FROM tbcat";
$result = mysqli_query($link, $qry) or die (mysqli_error($link));
$row = mysqli_fetch_array($result);
echo $row['total'];
?>
<label id="numberIndicator">1</label>
<?php
page indicator
<script type="text/javascript">
//page indicator
function add() {
var quantity_temp = document.getElementById("numberIndicator").innerText;
var quantity_int = parseInt(quantity_temp, 10) + 1;
document.getElementById("numberIndicator").innerHTML = quantity_int.toString();
}
</script>
it should be like this
First of all, your query looks wrong:
$qry = "SELECT COUNT qcatid FROM AS total FROM tbcat";
Should be more like this (since COUNT is a function)
$qry = "SELECT COUNT(qcatid) total FROM tbcat";
Well, the simplest way starting from the code you posted would be something like this (in your PHP):
Question <label id="currentPageIndicator"><?=$currentPage?></label> of <label id="totalPageIndicator"><?=$row['total']?></label>
Where $currentPage would be assigned a default of 1 and would either be stored in session or would be calculated by current row selection from your query that fetches data or something in that direction.

PHP selecting next array value of same id within the same page

Sorry if I asked a dumb question, quite new to PHP. I wanted to select the next array value within the same page and the same id, as all of them are from the same id. Mind if I ask for any help on this code? Thanks!
<?php
//get the id from the view page / search page e.g. url?id=1
$_SESSION['id'] = $_GET['id'];
$id = $_SESSION['id'];
include "backend/connect.php";
$sqlquestion = "Select * from game_question where game_id_fk = $id";
$result = mysqli_query($conn,$sqlquestion);
if(mysqli_num_rows($result)<=0){
echo "<script>alert('No questions found!');</script>";
}
while($row = mysqli_fetch_array($result)){
$question[] = $row['game_question'];
$qid[] = $row['game_question_id'];
}
?>
<?php
$current_index = array_search($qid, $question);
$next = $current_index + 1;
$prev = $current_index - 1;
?>
<?php if ($prev > 0): ?>
Previous
<?php endif; ?>
<?php if ($next < count($question)): ?>
Next
<?php endif; ?>
This is the table schema of game_question
WARNING
Concatenating query params into query string may lead to SQL injection, take a look here
A simple way to do that is to implement some sort of pagination, in which each page is exactly 1 item long, and pass the current page as a GET param.
You can implement it as a LIMIT clause on your query, like this:
$pos = (isset($_GET['pos']) && $_GET['pos']) ? $_GET['pos'] : 0;
$sqlquestion = "
Select *
from game_question
where game_id_fk = $id
LIMIT 1 OFFSET $pos
";
Then you have to calculare previous and next position based on the $pos variable and add them in the links as a query param, like url.php?id=1&pos=3;
Note that this way positions starts at 0
I would take an approach of querying the DB only once, so i assume the amount of questions belonging to one id is not too huge.
This way you can retrieve all the results and then use some front end magic to display these results with next/prev functionality. I wrote a sample where jQuery has your questions, so its up to you how you want to display them.
You can also look at Bootstrap (https://getbootstrap.com/), it has some cool features, so you could get PHP to loop your questions and write the HTML elements, then Bootstrap would do its magic displaying it
I've also added parameter binding to your query, this will prevent some SQL injections and should always be used
<?php
//get the id from the view page / search page e.g. url?id=1
$id = $_SESSION['id'] = $_GET['id'];
include "backend/connect.php";
$stmt = mysqli_prepare($con, "SELECT * FROM game_question WHERE game_id_fk = ?");
mysqli_stmt_bind_param($stmt, "s", $id);
$result = mysqli_stmt_execute($stmt);
$questions = array();
if(mysqli_num_rows($result)<=0){
echo "<script>alert('No questions found!');</script>";
die;
}
while($row = mysqli_fetch_array($result)){
$questions[$row['game_question_id']] = $row['game_question'];
}
?>
<!-- HTML -->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var questions = <?php echo json_encode($questions) ?>;
$.each(questions, function (i, elem) {
// do your stuff
});
</script>
</head>
<body>
</body>
Here's an example of bootstrap tabs with prev/next buttons: https://codepen.io/techiegang/pen/QjdgJJ

How Can I send $_POST with query string in a link

This is php code which checks if form(on same page) is posted and gets the result depending upon $_POST array if it is posted or returns all results from data base. this also sets $total variable containing number_of_pages later used for pagination
if(!isset($_POST['search']))
{
$id = (isset($_GET['id']) ? $_GET['id'].'0' : 10);
$id = $id-10;
$query = "select SQL_CALC_FOUND_ROWS * from feedbacks order by Date desc limit $id, 10 ";
}
else if (!empty($_POST['from']))
{
$timstmp = strtotime($_POST['from']);
$dt = date("Y-m-d H:i:s", $timstmp);
$id = (isset($_GET['id']) ? $_GET['id'].'0' : 10);
$id = $id-10;
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM `feedbacks` WHERE `Date` >= \"$dt\" order by Date desc limit $id, 10 ";
}
else if (!empty($_POST['name']))
{
$name = '%'.$_POST['name'].'%';
$id = (isset($_GET['id']) ? $_GET['id'].'0' : 10);
$id = $id-10;
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM `feedbacks` WHERE `name` LIKE '$name' order by Date desc limit $id, 10 ";
}
$result= mysqli_query($connection, $query);
$r = mysqli_fetch_array(mysqli_query($connection, 'SELECT FOUND_ROWS()'));
$total = ceil($r['FOUND_ROWS()']/10);
$feedbacks = array();
for ($i = 0;$row= mysqli_fetch_assoc($result); $i++)
{
$feedbacks[$i] = new FeedBack($row);
}
?>
These are the html links that are automatically generated depending upon the total number of pages which is calculated depending upon results from data base
<?php
if ($total>1)
{ ?> <div class="pagging">
<?php for( $i=$total; $i>=1; $i--)
{ ?>
<div class="right">
<a id="pagination" href="index.php?id=<?php echo $i; ?>"><?php echo $i; ?></a>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<!-- Table -->
On this page I'm implementing filters. User input data in the form and press search so depending upon the $_POST array the different results are loaded and variable $total containing num_of_pages is modified as the 1st block of php code shows now the first page displays 1st 10 results from data base using offset 0 or ofset = IDX10-10 if id is set but problem is that it only works for default results i.e when all results are displayed and filter is not applied but when user searches through a filtered 1st 10 filtered results are displayed but when user clicks the next page it does not work because $_POST is unset which was checked by the php If conditions in above php code. so my question is how can i send $_POST[] along with the id to make it work. Any help would be appreciated. Thanks.
You can't send POST variables through a link. You need to use GET.
Link
//the link will reflect some_page.php?name1=value1&name2=value2...etc
On the PHP side use the $_GET or $_REQUEST variable, instead of $_POST.

echo different fields in tabs

I'm trying to make a tab for my page, where each tab shows a different field of a mysql table row. I'd like to switch contents in the tab.
Every row has a different id, and I would like to make a tabbed design. The data should be chosen by the id of the table.
The tab works fine if i use just a simple text in the echo part, but I can't fetch the data from my database.
I tried this code, but it doesn't work.
<?php
if (isset($data[0]) && is_numeric($data[0]) ) {
$content = mysql_fetch_assoc ( mysql_query( "select id,tab_content_one,tab_content_two,tab_content_three,tab_content_four,tab_content_five from db_name where id = $data[0];") );
} else {
$content = mysql_fetch_assoc ( mysql_query( "select id,tab_content_one,tab_content_two,tab_content_three,tab_content_four,tab_content_five from db_name order by id asc limit 1;") );
}
switch($_GET['tabNum']) {
case 1: echo strip_tags($content['tab_content_one']); break;
case 2: echo strip_tags($content['tab_content_two']); break;
case 3: echo strip_tags($content['tab_content_three']); break;
case 4: echo strip_tags($content['tab_content_four']); break;
case 5: echo strip_tags($content['tab_content_five']); break;
}
?>
I don't know what's wrong with my code. Do you have any idea?
You've got to enclose the mysql_fetch_assoc into a while loop! For your code it will be something like this:
if (isset($data[0]) && is_numeric($data[0]) ) {
$sql = "select id,tab_content_one,tab_content_two,tab_content_three,tab_content_four,tab_content_five from db_name where id = $data[0];";
} else {
$sql = "select id,tab_content_one,tab_content_two,tab_content_three,tab_content_four,tab_content_five from db_name order by id asc limit 1;";
}
$result = mysql_query($sql);
while($content = mysql_fetch_assoc($result)){
switch($_GET['tabNum']) {
case 1: echo strip_tags($content['tab_content_one']); break;
case 2: echo strip_tags($content['tab_content_two']); break;
case 3: echo strip_tags($content['tab_content_three']); break;
case 4: echo strip_tags($content['tab_content_four']); break;
case 5: echo strip_tags($content['tab_content_five']); break;
}
}
Anyway it's suggested to you as mysql_fetch_assoc it's going to be deprecated starting from php 5.5.0 to use the mysql_PDO extension instead.

php include - how to make variables available where included?

I am trying to include a file which is scraping all my data from varrious websites, however its not working. Heres my code.
firstly, the scraping php file. named scrapedata.php
<?php
//Include the Simple HTML DOM to use its functions, used by other following scripts.
//navigate to the content of variable html and save it in price data variable
//get the whole html of the webpage into variable html
include 'simple_html_dom.php';
$html = file_get_html('http://www.play.com/Electronics/Electronics/4-/16230382/New-Apple-iPod-Touch-8GB-4th-Gen/Product.html?');
$price_data = $html->find('h6[id=bodycontent_0_middlecontent_1_ctl00_ctl00_product_ctl00__overview_ctl00__dataControl__price__headerSix',0)->plaintext;
//Amazon.co.uk scrape
$amazon_html = file_get_html('http://www.amazon.co.uk/New-Apple-iPod-touch-Generation/dp/B0040GIZTI/ref=br_lf_m_1000333483_1_1_img?ie=UTF8&s=electronics&pf_rd_p=229345967&pf_rd_s=center-3&pf_rd_t=1401&pf_rd_i=1000333483&pf_rd_m=A3P5ROKL5A1OLE&pf_rd_r=1ZW9HJW2KN2C2MTRJH60');
$amazon_pd = $amazon_html->find('b[class=priceLarge]',0)->innertext;
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($amazon_html);
$xpath = new DOMXpath($dom);
$expr = "/html/body/div[#id='divsinglecolumnminwidth']/form[#id='handleBuy']/table[3]/tr[3]/td/div/span";
$nodes = $xpath->query($expr); // returns DOMNodeList object
// you can check length property i.e. $nodes->length
//echo $nodes->item(0)->nodeValue; // get first DOMNode object and its value
$stock_data = $nodes->item(0)->nodeValue;
if ( $stock_data == "In stock." ) {
$stockyesno = "Yes";
} else {
$stockyesno = "No";
}
//Currys scrape
$currys_html = file_get_html('http://www.currys.co.uk/gbuk/apple-new-ipod-touch-8gb-4th-generation-07677427-pdt.html');
$currys_pd = $currys_html->find('p[class=prd-amount]',0)->plaintext;
$currys_stk = $currys_html->find('/html/body/div/div/div[2]/div/div/div[2]/div/ul[2]/li/span')->plaintext;
//span[class=icon icon-check]',0);
echo $currys_stk;
if ( $currys_stk == "Available for home delivery" ) {
$currys_stockyesno = "Yes";
} else {
$currys_stockyesno = "No";
}
//Argos scrape
$argos_html = file_get_html('http://www.argos.co.uk/static/Product/partNumber/9282197/Trail/searchtext%3EIPOD+TOUCH.htm');
$argos_pd = $argos_html->find('span[class=actualprice]',0)->plaintext;
//Ebuyer scrape
$ebuyer_html = file_get_html('http://www.ebuyer.com/product/237805');
$ebuyer_pd = $ebuyer_html->find('span[class=now]',0)->plaintext;
//PcWorld scrape
$pcworld_html = file_get_html('http://www.pcworld.co.uk/gbuk/apple-new-ipod-touch-8gb-4th-generation-07677427-pdt.html');
$pcworld_pd = $pcworld_html->find('p[class=prd-amount]',0)->plaintext;
?>
and then my page where its included, to then which its meant to access the data in the variables from the included file.
<?php include 'scrapedata.php';?>
<!-- MYSQL DATABASE CODE -->
<?php
$db_host = 'localhost';
$db_user = 'admin';
$db_pwd = '1admin';
$database = 'stock_checker';
$table = 'price_stock';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
?>
<!-- MYSQL DATABASE CODE END-->
//Insert the scraped data into the database.
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('Play.com', '$play_pd' )")
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price,stock) VALUES('Amazon', '$amazon_pd', '$stockyesno' )")
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price,stock) VALUES('Currys', '$currys_pd', '$currys_stk' )")
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('Argos', '$argos_pd' )")
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('eBuyer', '$ebuyer_pd' )")
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('PCWorld', '$pcworld_pd' )")
or die(mysql_error());
?>
<!-- MYSQL DATABASE % TABLE CREATION CODE -->
<?php
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<table width='650px'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td><b>{$field->name}</b></td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
Have I done this correctly ? I don't know if they would automattically be included, or they have to be made GLOBAL ?
This is a very bad idea.
You should be using functions; passing and returning values. Include files at the beginning of the script, call functions when needed. Do not put any freestanding (non-function) code in files you include.
(By the way, the next step is OOP and autoloaders.)
And in case you're wondering why this is a very bad idea: I've looked over your code 5 times now (though with no in-depth analysis) and still haven't figured out what variables you want to share between the two files. If I went line-by-line, I'd find it, but I don't want to go line-by-line. Neither do you, in 3 months, when you're updating the code. Make our job easier.
--
From a point of view, an object is a collection of functions and the state they share; so it's the third step here: no functions -> some functions -> functions grouped together in classes. Don't even know if it's any good, but PHP has this to say about OOP. Autoloading is the mechanism PHP uses to load classes on-demand, usually saving you from includes.
They don't need to be imported explicitly.
Try this example:
<?php
// a.php
$myVar = 123;
and
<?php
// b.php
include 'a.php'
echo isset($myVar)?'Included':'Not included';
Related to your posted code: I don't see where you add data to the database. Shouldn't you do that as well?
It's a bad idea to use DOM Parsing for such requests. Amazon released a simple API - read here: http://aws.amazon.com/de/
PHP variables in the included file will appear in the main file by the same name.
But in your code I don't see variables being reused at all? The scrape generates information in variables, then your main file reads an unrelated database table. The two operations need to relate somehow.

Categories