I have been trying for a while to figure out how to display data from a specific row within my database based on the ID.
Say I want the link to be survivaloperations.net/page/mso?p=contracts&id=#
where id=# is the ID of the row I am pulling data from in the database
How would I pull and display data from the database using a link like shown above?
I Tried to google it, but didn't really know what to google to find related things
Any help or links for references are appreciated!
Here is what I had tried:
<?php
if ($p == contracts) {
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
if ($id != 0):
// I assume this is a specific news item meaning you know it's ONE result
$query = 'SELECT * FROM contracts WHERE id=' . $id . ' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
endif;
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while ($row = mysql_fetch_array($result)) {
// and use'em however you wish
echo("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row2[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a
href='#'>$row2[unit]</a><br/>by: <a
href='http://www.survivaloperations.net/user/$row2[userid]-$row2[username]/'>$row2[username]</a>
</div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row2[callsign]<br/>
Urgency: $row2[urgency]<br/>
Location: $row2[location]<br/>
Grid: $row2[grid]<br/>
Enemy Activity: $row2[enemy_activity]<br/>
Hours Since Lasrt Contact: $row2[contact_hours]<br/><br/>
Supplies Requested: $row2[supplies]<br/>
Comments: $row2[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
?>
I figured it out with my original code:
if ($p == contracts)
{
$cid = $_GET['id']; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
$query = 'SELECT * FROM contracts WHERE id='. $cid .' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while($row = mysql_fetch_array($result)){
// and use'em however you wish
echo ("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a href='#'>$row[unit]</a><br />by: <a href='http://www.survivaloperations.net/user/$row[userid]-$row[username]/'>$row[username]</a></div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row[callsign]<br />
Urgency: $row[urgency]<br />
Location: $row[location]<br />
Grid: $row[grid]<br />
Enemy Activity: $row[enemy_activity]<br />
Hours Since Lasrt Contact: $row[contact_hours]<br /><br />
Supplies Requested: $row[supplies]<br />
Comments: $row[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
Google for $_GET variable in PHP and have a look at database connection using PDO or mysqli
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/pdo.query.php
After you added code:
mysql_* is deprecated. Try to switch to either mysqli or PDO and have a look at the link above.
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) ? abs( (int) $_GET['id']) : 0;
if($id == 0) {
echo 'Invalid ID';
return;
} else {
$query = "SELECT * FROM `table` WHERE `id`=". $id;
$get = $db->prepare($query);
if($get) {
$get = $db->query($query);
$r = $get->fetch_array(MYSQLI_ASSOC);
var_dump($r);
} else {
echo 'Could not connect to the database';
return;
}
I've mixed two styles of MySQLi, which isn't really standard, but it should suffice for this example.
http://php.net/mysqli
(Ensure you have database connection)
$row2 should be $row
And things like
$row[contract_type]
Better to be
$row['contract_type']
And try to move to mysqli or PDO as advised by earlier poster
Related
I am fairly new to PHP and mySQL and have small issue I am busy trying to create a 4 column layout with using echo and currently I have managed to achieve this with with a mySQL database but the last column requires and additional style in the div class. With my Limited knowledge I thought of trying a count using one of the solutions I found on the forum, but I think I may be using it wrong. my idea is to echo the database array, then do a count and echo the same content block but the with additional css element in div class. Your help is greatly appreciated. if this question has been asked before please accept my apologies I am just under a lot of pressure to get it resolved.
SEE CURRENT PHP Code Below
<?php
$conn = mysqli_connect('localhost', 'root', 'password')
or die ( mysql_error());
$rs = mysqli_select_db($conn, 'database name' ) or die
( mysql_error());
$query = "SELECT * FROM database name";
$rs = mysqli_query( $conn, $query ) or die
( mysql_error());
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH))
{
$id = $row['id'];
$image = $row['image'];
$product = $row['product'];
$code = $row['code'];
$material = $row['material'];
$sizes = $row['sizes'];
echo "
<div class='percent-one-fourth'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
$i = 0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH)){
if($i++ % 4 == 0) {
echo "
<div class='percent-one-fourth column-last'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
}
mysqli_close($conn);
?>
As you're new to PHP, it's really important that you understand why your code isn't working properly. So, let's step over it and describe it in brief, simple English:
Connect to MySQL
Run a database query which has multiple rows as its response
Whilst there are more rows to go..
Output every row
Whilst there are more rows to go.. [!] Always false - we already used them all up
Output every 4th result [!] Vars like $image also aren't defined here
So, because of the way how mysqli_fetch_array works, you can hopefully see that we need to loop using it only once. This is also great for you, because it fits with the DRY (don't repeat yourself) principle.
Edit: You were also mixing MySQL API's; mysql_error is very different from mysqli_error.
So instead, during our one loop, we'll check if we're on the 4th row, and react differently. That results in something like this:
<?php
// 1. Connect to MySQL
// (this should be in a separate file and included so you don't repeat it)
$conn = mysqli_connect('localhost', 'root', 'password')
or die ( mysqli_error()); // <-- *mysqli*
$rs = mysqli_select_db($conn, 'database name' ) or die
( mysqli_error());
// 2. Run the query which has multiple rows as its response:
$query = "SELECT * FROM database name";
$rs = mysqli_query( $conn, $query ) or die
( mysqli_error());
// 3. Whilst there are more rows to go..
$i=0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH))
{
// Get easier references to various fields:
$id = $row['id'];
$image = $row['image'];
$product = $row['product'];
$code = $row['code'];
$material = $row['material'];
$sizes = $row['sizes'];
// Start outputting this row:
echo "<div class='percent-one-fourth";
// The important part! We check here in this single loop:
if($i++ % 4 == 0){
// Every 4th row - output that extra class now!
echo " column-last";
}
// Output everything else:
echo "'>
<div class='catalogue_content'>
<img src='bridal_gowns/$image.jpg' alt='Bridal Gown Catalogue - $product'>
<h3>$product</h3>
<div class='content'>
<p id='content'><span style='font-weight:bold; color:#969;'>Code:</span> $code<br>
<span style='font-weight:bold; color:#969;'>Material:</span> $material<br>
<span style='font-weight:bold; color:#969;'>Sizes Available:</span> $sizes
<br>
<br>
</p>
<a href='mailto:lizette#bridalalchemy.co.za; raymond#bridalalchemy.co.za?subject=Enquiry from Web / Product: $product, Code: $code;'><img src='enquire.jpg'></a>
</div>
</div>
</div>
";
}
// Tidy up:
mysqli_close($conn);
?>
Your code is echoing only for the 4th column. For columns 1, 2, and 3, you need to add an else clause.
Optional: Besides instead of echoing you could close the php tag (?>) and write the html directly.
...
$i = 0;
while( $row = mysqli_fetch_array($rs, MYSQLI_BOTH)){
if($i++ % 4 == 0) {
echo "html for the 4th column";
}else{
echo "html for column 1, 2, and 3";
}
}
I need to display a list of results form a survey on a PHP page then export them to a CSV file. The list also acts as a summary that can be clicked thorugh to the full result.
I have all that sorted but now I need to have the CSV export by a check bx selection so that we dont need to download the entire databse each time just the ones we need.
My code so far below.
<div class="resultsList">
<h1>PEEM Results List</h1>
<a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
<!-- Export CSV button -->
<h3 class="resultsbydate">All results by date</h3>
<div class="resultsListHeader">
<div class="clientidTab">Agency</div>
<div class="clientidTab">Family ID</div>
<div class="clientidName">Name</div>
<div class="clientidTab">Date</div>
<div class="clientidTab"></div>
</div>
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<div><input type=\"checkbox\" name=\"xport\" value=\"export\"><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent’s Review</strong></a></span>";
echo "<span><strong>View Results</strong></span>";
echo "</div>";
}
?>
</div>
</div>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query1 = mysql_query("select * from results where survey_id=$id", $connection);
while ($row1 = mysql_fetch_array($query1)) {
?>
<?php
}
}
?>
<?php
mysql_close($connection); // Closing Connection with Server
?>
And the downloadcsv.php
<?php
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);
$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
$query = "SELECT * FROM results";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
?>
Any help with this would be great, cheers
Updated with a screenshot of what I am trying to achieve
The initial result set needs to be wrapped in a form which POST to the next page.
The Checkbox must send an array of ids to the export script.
<input type='checkbox' name='xport[]' value='ID_OF_THE_ROW_HERE'>
The [ ] after xport means that $_POST['xport'] will be an array of values.
The export page can collapse that array of ids into a comma separated string and to be used the query:
SELECT * FROM results WHERE id IN (4,7,11,30)
<form method="POST" action="downloadcsv.php">
<h1>PEEM Results List</h1>
<a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
<!-- Export CSV button -->
<h3 class="resultsbydate">All results by date</h3>
<div class="resultsListHeader">
<div class="clientidTab">Agency</div>
<div class="clientidTab">Family ID</div>
<div class="clientidName">Name</div>
<div class="clientidTab">Date</div>
<div class="clientidTab"></div>
</div>
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<div><input type='checkbox' name='xport[]' value='{$row['client_id']}'><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent’s Review</strong></a></span>";
echo "<span><strong>View Results</strong></span>";
echo "</div>";
}
?>
</div>
</form>
Change $row['client_id'] to the correct value
Then in the export script:
<?php
/*
Expecting $_POST['xport'] array of row ids
*/
if( !isset($_POST['xport']) OR !is_array($_POST['xport']) ) {
exit('No rows selected for export');
}
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);
$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
//Cast all ids to integer
$ids = $_POST['xport'];
array_walk($ids, function(&$value, $key) {
$value = (int)$value;
});
$ids = implode(', ', $ids);
$query = "SELECT * FROM results WHERE id IN ($ids)";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
?>
So if I'm getting this correctly, you just need to be able to check checkboxes to select the databses ($rows) you want to insert into the csv file....
Every checkbox that you checked will be in the $_POST variable, so:
1st you make an array with all the names of checkbox options (databases), for example
$all_db = ['database1', 'database2', 'database3'];
2nd you loop through each of the values in $all_db and check if they exist in the $_POST array, if they do, then you can export the row
foreach( $all_db as $db_check ) {
if ( array_key_exists( $db_check, $_POST ) {
// EXPORT TO CSV
}
}
Don't forget ! This means the "name" attribute of the checkbox should be the name of the database.
If you don't want to have a static list of databases (i.e. there is a possibillity of them having different names in the future / there will be moreor maybe less etc then let me know i can edit my answer if needed :) )
( If you use the $_GET variable, then you can do the same thing just change $_POST to $_GET)
Know though that $_GET comes over as a bit amateuristic for the enduser if he gets a thousand variables in his URL,
$_POST is often a better alternative since it is hidden and cleaner for the enduser...
EDIT: UPDATING ANSWER (SEE COMMENT)
So basically you need people to be able to choose what rows they export from you dB...
First of all this means we need a unique ID for each row,
This can either be a column used solely for that (i.e. ID column with auto increment and unique attribute)
Or this can be a column you already have, just make sure it's a unique column so we don't get dupliate values (you'll see why below)
Then we give the value of this unique ID column to the checkbox's "name" attribute, and using jquery / php we append / prepend a static string...
For example, using your family ID:
"rownumber_" + $family_ID
This gets us (again using your example) :
$_POST[] = ['rownumber_123456' => 1, 'rownumber_0000000' => 1, .....]
So then in your PHP file you just do the following to add the correct lines to your CSV:
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['your_row_id'], $_POST) {
fputcsv($fp, $row);
}
}
-- Again using your example with family_ID : --
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['family_ID'], $_POST) {
fputcsv($fp, $row);
}
}
EDIT: Updating answer for comment no.2
So little sidenote if you are going to loop through html using php
(i.e. loop trhough db rows and print them out in an orderly fashion)
Then you propably want to use the ":" variants of the loops,
While() :
for() :
foreach() :
if () :
.....
These variants allow yu to close the php tag after the ":" and whataver html / css / php / jquery you put in the condition / loop will be executed like normal...
For example you can do :
<ul>
<?php foreach ($row as $columnkey => $columnvalue): ?>
<img src="whateveryouwant"?>
<li class="<?php echo $columnkey;?>">This is my value: <?php echo $columnvalue; ?></li>
<?php endforeach; ?>
</ul>
When you do it this way it's much cleaner and you won't have any problems using double quatation signs and all that stuff :)
So using that method here is how your displayed list would look like in code:
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) :
?>
<div>
<input type="checkbox" name="<?php echo $row['family_id']; ?>" value="export">
<span><?php echo $row['client_id']; ?></span>
<span><?php echo $row['family_id']; ?></span>
<span><?php echo $row['firstname'] . " " . $row['lastname']; ?></span>
<span><?php echo date("d F Y",strtotime($row['peemdate']); ?></span>;
<span>
<a class="parents-button" href="peem-parent-repsonses.php?id=<?php echo $row['survey_id']; ?>">
<strong>Parent’s Review</strong>
</a>
</span>
<span>
<a href="peem-repsonses.php?id=<?php echo $row['survey_id']; ?>">
<strong>View Results</strong>
</a>
</span>
</div>
<?php endwhile; ?>
</div>
Like this the checkbox will get the name of the family ID, and so in your csv.php you can use this code :
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['family_ID'], $_POST) {
fputcsv($fp, $row);
}
}
Since now it will check for each row wether the family ID of the SQL row is posted as a wanted row in the $_POST variable (checkbooxes) and if not it won't export the row into the csv file ! :)
So there you go ^^
EDIT 3: Troubleshooting
So there are a couple of things that you do in this function,
the form,
Do the checkboxes in your html form have the family_ID in their name attribute ?
(i.e. <input type="checkbox" name="<?php echo $row['family_id']; ?>".... check if the name attribute is really filled )
you post stuff from a form, (your checkboxes and stuff)so let's see what actually gets posted,
die(print_r($_POST)); - This means you want php to die after this line (stop working at all), then print out a variable as is (sort of xml format you'll see)
So then you will get a whole bunch of information, if you want to see this information in a nicely formated way, just right click inspect element on it :)
Then see how your checkboxes are coming out of the $_POST variable,
(they should have the family_ID as a key and a value of 1)
If that's all ok, then check your row['family_ID'] variable see if the family_ID is filled correctly, do the same with your whole $row variable, in fact check every variable you use in csv.php and then check why the key does not exist in the array you are searching for :)
Also dont forget to check that you filled the array_key_exists( has a key FIRST and an array[] LAST )
I can't help you directly with this , since this will propably be a faulty variable or a mistake in your form so try to find this yourself, if still nothing , post these variables values:
$_POST
$row
and the full HTML of your form
I am trying to fetch data from the database, but not retrieve data particular id.
this is my one page:
example1.php
<a style="color: #3498DB;" class="btn btn-default" href="http://www.example.com/getafreequote?id=<?php echo $row['product_id']; ?>">Get Quote</a>
example2.php
<?php
$id = isset($_GET['id'])?$_GET['id']:'';
$query = "SELECT * FROM oc_product_description WHERE product_id=$id";
$run1 = mysql_query($query);
while ($fetch1 = mysql_fetch_object($run1)){
?>
<div class="col-xs-12 col-sm-6">
<label for="GetListed_product"></label>
<input class="le-input" name="product" id="GetListed_product" type="text" value="<?php
$b = $fetch1->product_id;
$q2 ="SELECT product_id,name FROM oc_product_description WHERE product_id = $b";
$q3 = mysql_fetch_assoc(mysql_query($q2));
echo $q3['name'];
?>" >
<span id="productmsg" class="msg"></span>
</div>
<?php
}
?>
</div>
but didnot get data form particular product id. I have got error show like this
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in example.com/example2.php on line 71
Please don't use mysql functions they are deprecated. Use mysqli or PDO for database operations. Also the way you write the query string makes it easy for an SQL injection, use prepared statements instead. Here is an example:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch();
You can also use prepared statements for inserting or updating data. More examples here
As said by FilipNikolovski, don't use mysql functions they are deprecated. Use mysqli or PDO for database operations.
For your problem, the function mysql_query is returning false. The query is not returning any result and thus mysql_query is returning false.
Make a check like this:
$query = "SELECT * FROM oc_product_description WHERE product_id=$id";
$run1 = mysql_query($query);
if($run1)
{
if(mysql_num_rows($run1) > 0)
{
while ($fetch1 = mysql_fetch_object($run1))
{
// your stuff here
}
}
else
{
echo "No records found.";
}
}
else
{
echo "Error in query : ".mysql_error();
}
This will help you to detect the problem and to solve as well.
I am trying to make a page which has to get data from two tables. and display on a page. this displayed data is an array. for example if the displayed data is say USA which come from Table A,and if you click on USA...then it should go to Table B and get all the states from Table B related to USA and display it on the page. so how to join the tables?
the code used is as below:
<?php
require("libs/config.php");
$pageDetails = getPageDetailsByName($currentPage);
$stateDetails = getStateDetailsById($page_id);
include("header.php");
?>
<div class="row main-row">
<div class="col-md-8">
<section class="left-content">
<h2><?php echo stripslashes($pageDetails["page_title"]); ?></h2>
<?php echo stripslashes($pageDetails["page_desc"]); ?>
<!--New-->
<?php
$page_id = $pageDetails["page_id"];
if ($_GET["id"] <> "")
{
// if we are on page.php page. get the parent id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_PAGES . " WHERE status = 'A' AND parent = :parent ORDER BY sort_order ASC";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($pageDetails["parent"]));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
elseif ($page_id <>"")
{
// On any other Page get the page id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_PAGES . " WHERE parent = :parent";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($page_id));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
?>
<div class="col-sm-12">
<?php
if (count($pageResults) > 0)
{
?>
<section>
<h2>States</h2>
<div>
<div class="row">
<?php foreach ($pageResults as $rs)
{ ?>
<div class="col-sm-3">
<ul class="state">
<li class="state">
<div class="state-dist"><h3><?php echo stripslashes($rs["page_title"]);?></h3>
<div class="state_img"><img src="images/<?php echo stripslashes($rs["page_image"]);?>"height="50" width="180"</div>
<br />
<br />
<div class="page-actions">
More Details
</div>
</li>
</ul>
</div>
<?php } ?>
</div>
</div>
</section>
<?php } ?>
</section>
</div>
So,
when i click on the link created by the last part of the code then it should go to TABLE.STATES fetch the records and display it. Currently this code goes to the same table TABLE_PAGES.
I know i have to use table joins but I am not able to code it.
Currently this code goes to the same table TABLE_PAGES.
As far as I think, you should change TABLE_PAGES to TABLE_STATES in the following part of your code:
elseif ($page_id <>"")
{
// On any other Page get the page id and fetch their related subpages
$sql = "SELECT * FROM " . TABLE_STATES . " WHERE parent = :parent";
try
{
$stmt = $DB->prepare($sql);
$stmt->bindValue(":parent", db_prepare_input($page_id));
$stmt->execute();
$pageResults = $stmt->fetchAll();
}
catch (Exception $ex)
{
echo errorMessage($ex->getMessage());
}
}
I'm assuming you'll be running the following SQL code:
SELECT * FROM TABLE_STATES WHERE TABLE_STATES.page_id = TABLE_PAGES.page_id
which you can execute to get a list of all the states belonging to the parent (TABLE_PAGES) table.
TIP: Always try to use table names that represent real-world entities AND serve the purpose of the actual data that you want to store. In your case TABLE_COUNTRIES would be a more conventional name for a table that represents the entity country.
You could also run a left join as such:
SELECT TABLE_STATES.* LEFT JOIN TABLE_COUNTRIES ON TABLE_COUNTRIES.page_id = TABLE_STATES.page_id AND TABLE_COUNTRIES.page_id = <your provided value>
I have this PHP code :
$query = "SELECT * FROM news WHERE news_active = 1 AND news_type = 1 ORDER BY id DESC";
$q2 = "SELECT * FROM st_photos WHERE id = 4 LIMIT 1";
$r2 = mysql_query($q2);
$row22 = mysql_fetch_array($r2);
$news_set = mysql_query($query);
$news_set2 = mysql_query($query);
if (mysql_num_rows($news_set) != 0) {
$r = mysql_fetch_array($news_set);
echo "<div id=\"d_coll\">
<div id=\"top_text\">$row22[img]</div>
<div id=\"d_image\"><img id=\"larg_p2\" src=\"photos/$r[news_image]\" width=\"320\" height=\"250\" border=\"0\"></div>
<div style=\"width:300px\"><div id=\"n_text2\">$r[news_part_en]</div>
</div>
</div>";
}
if (mysql_num_rows($news_set2) != 0) {
while ($news = mysql_fetch_array($news_set2)) {
echo "<div id=\"n_col\">
<div id=\"n_tittle\">$news[news_tittle_en] <img src=\"images/bu3.png\" border=\"0\" align=\"middle\"></div>
<div id=\"im\"><img onMouseOver=\"MM_swapImage('larg_p2','','photos/$news[news_image]','imgs[$news[id]]','','photos/$news[news_image]',1);up2('$news[news_part_en]')\" onMouseOut=\"MM_swapImgRestore()\" name=\"imgs[$news[id]]\" id=\"imgs[$news[id]]\" src=\"photos/$news[news_image]\" width=\"50\" height=\"50\"></div>
<div dir=\"ltr\" id=\"n_div\">$news[news_part_en] <div class=\"mo\">MORE</div></div>
</div>";
}
echo "<div align=\"right\" class=\"arr\"><img src=\"images/prev.png\"> <img src=\"images/next.png\"></div>";
}
There are 2 images at the end of the code (prev & next), I want to use them to do pagination but I don't want to view any numbers, only these 2 images.
How I can do that?
I think we can do that by using JQuery library, but I don't know how to use it.
Thanks in advance.
you can use one of many plugins, for example here .
you must just remoove thе numbers. you can, i believe;)
or you can write the script by yourself.
i'll give you only an idea. let's assume you have 30 rows( from DB).put them into <div> tags, and increase the id of div. the display proparty of first <div> you must set to '', and all others to none. and then, onclick on your buttons, you just change display proparty of div elements...