Transferring array to next page - php

I found some similar problems here, but none of them does really fit to my problem.
I want to create an array consisting of entries from my database. My code looks like that:
<?php
include ("../script/db_connect.php");
$select_questions = 'select * from users ';
if (isset($_POST["own"]) && $_POST["own"] == "No") {
$select_questions .= 'where creator != '
. $_SESSION["id"];
}
$select_questions .= ' limit '
. $number;
$questions_result = mysqli_query($con, $select_questions);
while ($row = mysqli_fetch_assoc($questions_result)) {
$questions[] = $row;
}
$_SESSION["questions"] = $questions;
mysqli_close($con);
?>
After that, I want to create an array, which will later be saved as a $_SESSION variable. To test my code, there is another page, where I want to echo my array. On the other page, I use the following php code:
<?php echo var_dump($_SESSION["questions"]); ?>
I tried different versions, but it still does not really work. I'm pretty new to PHP, so any help is highly appreciated!

Don't forget to start session by adding this line at the top of your 2 scripts :
<?php
session_start();

Related

Grab variable from clicked anchor tag

I'm currently working on producing a basic content management system. In this code I'm grabbing a list of pages from the database 'posts' and then echoing them out. The purpose of the list is for users to be able to select an existing page and then edit the title & content, however I'm unsure on how I can take data from the selected link and then make my page-edit.php show the correct content to edit accordingly. I've assigned the variable $i to each of the anchor tags which increments throughout the while loop, ideally I'd use $i to SELECT the correct page from the database. I'd like to avoid using jQuery, although I'm assuming that's going to be suggested. Any insight would be great, thanks in advance.
<?php
$connection = mysql_connect('localhost', 'root', 'root');
mysql_select_db('posts');
$query = "SELECT * FROM pages";
$result = mysql_query($query);
$i = 0;
while($row = mysql_fetch_array($result)){
$i++;
echo '' . $row['page_title'] . ' - ' . $i . '' . '</br>';
}
mysql_close();
?>
Use the $i as a GET id variable in the link within the while loop:
echo '<a href="edit-page.php?id=' . $i . '>' . $row['page_title'] . ' - ' . $i . '</a>' . '</br>';
Then you can check for $_GET['id'] so that you know what id/page is to be edited and get the data for that from the database:
if (!empty($_GET['id'])) {
$query = 'SELECT * FROM pages WHERE id=' . $_GET['id'];
...
// Show the form populated with data from the above query.
}
I've kept this very simple to get you started.
Don't forget to look into protecting against SQL Injection and moving away from the deprecated MySQL API to use the MySQLi API or MySQL PDO.
Using this method, you'll need a to make an edit page for each page.
Main php file
<?php $db = mysqli_connect("localhost","user","pass","name");
foreach($this->db->query("SELECT * FROM pages") as $row): ?>
<a onclick="loadPage(<?php echo $row['id']; ?>)">
<?php echo $row['page_title']; ?>
</a>
<?php endforeach; ?>
<script>
function loadPage(id){
$.get('handler.php', { param: id })
.done(function (loaded){
document.getElementById("example").innerHTML = loaded;
});
}
</script>
Handler php file
<?php if(isset($_GET['param'])):
foreach($this->db->query("SELECT * FROM pages") as $row):
catch($_GET['param']){
case 1:
require_once 'edit-data.php';
break;
case 2:
require_once 'edit-data-two.php';
break;
default:
break;
}
endforeach; ?>
edit-data.php = edit the page X
edit-data-two.php = edit the page Y

How do I display a table using an explode or is there something else to suggest?

First I want to explain my application:
I have created an application for my QA work. The application generates a document gets saved as a pdf and added to the server. I have a dynamic table in it that gets save to the database using the implode function separating it as with a comma in the same row as the test case on the database.
It all works fine, but when I want to view the test case I am having trouble to figuring out how to get it to display. I have read plenty of scenarios to use the explode but no luck...
<?php include 'app_database/database.php'; ?>
<?php
if(isset($_POST)){
$step = $_REQUEST['step'];
$url = $_REQUEST['url'];
$pass_fail = $_REQUEST['pass_fail'];
$comment = $_REQUEST['comment'];
$sql1 ="UPDATE qa_testing_application SET step='".implode(',',$step)."',url='" . implode(',',$url) . "',pass_fail='" . implode(',',$pass_fail) . "',comment='" . implode(',',$comment) . "' WHERE test_case_name='$test_case_name'";
$result= mysqli_query($database, $sql1) or die(mysqli_error($database));
}
?>
I am inserting it this way. And i would like to retrieve it from the DB.
I would love to display it as follows:
Please see the link http://i.stack.imgur.com/6aglk.jpg
At the moment i am trying to test and figure out how to display it:
Not sure how to implement a for or foreach function in here as well if thats needed.
$countsteps = 0;
$counturls = 0;
$countpass_fails = 0;
$countcomments = 0;
$test_case_number = '21';
$select_tbl=mysqli_query($database,"select * from qa_testing_application WHERE test_case_number='$test_case_number'");
$result = mysqli_query($database, $sql1) or die(mysqli_error($database));
while($fetch=mysqli_fetch_object($result))
{
$step=$fetch->step;
$url=$fetch->url;
$pass_fail=$fetch->pass_fail;
$comment=$fetch->comment;
$steps=explode(",",$step);
$urls=explode(",",$url);
$pass_fails=explode(",",$pass_fail);
$comments=explode(",",$comment);
echo '<td>'.$steps[$countsteps++].'</td>';
echo '<td>'.$urls[$counturls++]."</td>";
echo '<td>'.$pass_fails[$countpass_fails++]."</td>";
echo '<td>'.$comments[$countcomments++]."</td>";
}
So how would I get this to display in a table?
edit:
Oh and this is the error that I get:
Undefined Offset
This error simply says there is no such key exists into given array or you're trying to fetch a value from non-array variable.
To show data into tabular format, you don't need to explode data coming from db. They are already concatenated.
So to show data from db, modify your code as show below:
$test_case_number = '21';
$select_tbl=mysqli_query($database,"select * from qa_testing_application WHERE test_case_number='$test_case_number'");
$result = mysqli_query($database, $sql1) or die(mysqli_error($database));
echo '<table>';
echo '<th>Step</th><th>Url</th><th>Pass/Fail</th><th>Comment</th>';
while($fetch=mysqli_fetch_object($result))
{
echo '<tr>';
echo '<td>'.$fetch->step.'</td>';
echo '<td>'.$fetch->url.'</td>';
echo '<td>'.$fetch->pass_fail.'</td>';
echo '<td>'.$fetch->comment.'</td>';
echo '</tr>';
}
echo '</table>';

My array won't echo a value for some reason

I have a database that holds thousands of structures. The structures are searchable by choosing the "area" first, then selecting the "block_number". My first page allows the user to select the area, the area is then passed through the url to the next page. The next page uses php to pull up the blocks in that area. I'm trying to echo the "area" and "block_number" in the results. The my query works just fine but, for some reason I can't display the "area" in the results. See the code below.
<?
include("conn.php");
include("pl_header.php");
$area = mysql_real_escape_string($_GET['area']);
$wtf = '$area';
?>
<h3>Choose A Block Number in<br> <?=$area?></h3><br>
<center>
<?php
$tblWidth = 1;
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
$i = 1;
// Check to see if any results were returned
if(mysql_num_rows($sql) > 0){
echo '<div class="redBox extraIndent">';
// Loop through the results
while($row = mysql_fetch_array($sql)){
echo ''. $row['area'] .''. $row['block_number'] .'';
if($i == $tblWidth){
echo '';
$i = 0;
}
$i++;
}
echo '';
}else{
echo '<br>Sorry No Results';
}
?>
</div>
</body>
</html>
My issue is where you see '. $row['area'] .' displays nothing, but the '. $row['block_number'] .' works just fine.
Your query is only selecting block_number.
Try changing:
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
To:
$sql = mysql_query("SELECT DISTINCT block_number, area FROM platform_locations WHERE area='$area'");
Edit: If you have this issue in the future try var_dump($row); to see what the array contains. This would show you that you only have access to the block_number and not the area.
Double edit: I didn't notice, but the other answer is right about the $area var- you've already got the $area saved, use that variable instead of the return from the DB as it's already in memory. If this could change per record, it'd be prudent to use the record's area variable to make your code more reusable. However, in this particular case, your SQL statement has the area in the where clause, so it wont vary unless you attempt to use portions of this code elsewhere.
Your SQL query is only selecting block_number, so that's the only field that will be in the $row array. You've already got area as a variable $area so use that, not $row['area'].

Dynamic url or pages in php

Well it's been my very first initiative to build a dynamic page in php. As i'm a newbie in php, i don't know much about php programming. i've made a database named "dynamic" and it's table name "answer" after that i've inserted four fields namely 'id', 'A1','A2', 'A3'.
I inserted the value in id=1 which are A1=1,A2 and A3-0,
In id=2, i have inserted A1=0, A2=1, A3=0
In id-3, i have inserted A1 and A2=0 A3=1
So now what i wanted is whenever i will click on the link of id=1 then it will display the content of id=1 and so on...
What i've done so far are:-
$conn= mysql_connect("localhost","root", "");
$db= mysql_select_db("dynamic", $conn);
$id=$_GET['id'];
$sql= "select * from answer order by id";
$query= mysql_query($sql);
while($row=mysql_fetch_array($query, MYSQL_ASSOC))
{
echo "<a href='dynamic.php?lc_URL=".$row['id']."'>Click Here</a>";
if($row['A1']==1)
{
echo "A1 is 1";
}
else if($row['A2']==1)
{
echo "A2 is 1";
}
else if($row['A3']==1)
{
echo "A3 is 1";
}
else {
echo "Wrong query";
}
}
?>
When i've executed this codes then it is showing me the exact id and it is going to the exact id but the values has not been changing..
I want whenever i will click on the id then it will display the exact value like if i click on id=2 then it will echo out "A2 is 1" nothing else....
Can anyone please help me out?
I also have noticed about
$id=$_GET['id'];
what is it and how to use it. Can anyone explain me out..
Thanks alot in advance:)
It may be best to start here to get a good understanding of php, before diving so deep. But to answer the specific questions you asked here...
The php $_GET variable is defined pretty well here:
In PHP, the predefined $_GET variable is used to collect values in a
form with method="get".
What this means is that any parameters passed via the query string (on a GET request) in the URL will be accessible through the $_GET variable in php. For example, a request for dynamic.php?id=1 would allow you to access the id by $_GET['id'].
From this we can derive a simple solution. In the following solution we use the same php page to show the list of items from the answer table in your database or single row if the id parameter is passed as part of the url.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer';
if ($_GET['id']) {
$query .= ' WHERE id = '.$_GET['id'];
} else {
$query .= ' ORDER BY id';
}
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else if ($res->num_rows == 1) {
// Display Answer
$row = $res->fetch_assoc();
echo '<h3>Answer for '.$row['id'].'</h3>';
echo '<ul>';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'</li>';
}
echo '</ul>';
}
?>
</body>
</html>
OK, this might not be exactly what you are looking for, but it should help you gain a little better understanding of how things work. If we add a little javascript to our page then we can show/hide the answers without using the GET parameters and the extra page request.
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer ORDER BY id';
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'';
echo '<ul id="answers_'.$row['id'].'" style="display:none;">';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
echo '</li>';
}
echo '</ul>';
}
?>
<script>
function toggleAnswers(answer) {
$('#answers_' + answer).toggle();
}
</script>
</body>
</html>
There are many more solutions, each more complicated that what I've presented here. For example we could set up an ajax request to load the answers into the list page only when an item is clicked. My advice is to go through some beginner tutorials on php and look at some of the popular PHP frameworks: Zend, CodeIgniter, CakePHP, etc. Depending on what you overall goal is, one of these might really help you get there faster.
Be warned that the code provided here is only an example of how to accomplish what you were asking. It definitely does not follow all (if any) best practices.

Need a Pagination PHP code to integrate with my SEARCH php script

It's been a month and am really messed up trying to integrate a php pagination code to my search script. Referred to most of the tutorials Googling, but in vain. Any help would be much appreciated. Here I go...
<?php
ob_start();
session_start();
$_GET['term'] = trim($_GET['term']);
$output = preg_replace('!\s+!', ' ', $_GET['term']);
if(empty($_GET['term'])|| preg_match("/^[#!#\$\^%&*()+=\-\[\]\\\';,\.\/\{\}\|\":<>\?\ _ ]+$/i", $_GET['term']) || $output== ' ' || $_GET['term']== "%24_GET%5B%27term%27%5D")
{
echo "<BR>";
echo "<BR>";
echo("Please enter a Valid Search term");
}
else
{
mysql_connect("localhost", "root", "root");
mysql_select_db("search");
$_GET['term'] = explode(' ', $_GET['term']);
foreach($_GET['term'] AS $_GET['term'])
{
$_GET['term'] = trim($_GET['term']);
$sql = mysql_query("SELECT DISTINCT * FROM searchengine WHERE pagecontent LIKE '%" . str_replace(' ', "%' AND pagecontent LIKE '%", $_GET['term'])."%' LIMIT 0,10");
while($ser = mysql_fetch_array($sql)) {
echo "<BR>";
echo "<b><u><a href='$ser[pageurl]'>$ser[title]</a></u></b>";
echo "<BR>";
echo("<span class='style_block'>{$ser['pagecontent']}</span>");
echo "<BR>";
echo ("<a href='$ser[pageurl]'>$ser[pageurl]</a>");
echo "<BR>";
echo "<BR>";
}
}
$count=mysql_num_rows($sql);
if($count==0)
{
echo "<BR>";
echo "<BR>";
echo "Sorry, No News material was found... Please refine your search criteria and try again.";
}
}
?>
Apart from the problems Luc M has mentioned in his comment (which you should certainly resolve before moving forward), you are almost there.
You need to consider a couple of points, really: How many records to display per page, and what page you are on. These will dictate the records you need to retrieve and display. So, how do you go about this?
The first point is covered in your code already through use of the LIMIT clause in your SQL query. The second point is a tiny bit more complex to start with. You need a way of identifying the page you are on. This is probably easiest to identify through a GET variable, for example http://site.com/search.php?page=2. Now, for implementing this, you want something along these lines:
$recordsPerPage = 10; // although you may want to have this as a GET or POST variable as well, so the user can decide
if(isset($_GET['page']) // this ensures a default value
{
$currentPage = $_GET['page'];
}
else
{
$currentPage = 1;
}
Then, for your SQL query, you want to build something like this:
$query = "SELECT * FROM table_name LIMIT " . $recordsPerPage . " OFFSET " . ($currentPage - 1)*$recordsPerpage . ";";
The OFFSET clause of SQL along with LIMIT basically says "Select this many records, starting from result number x". You offset on $currentPage - 1 because the first page doesn't want an offset, and the second page only wants an offset of however many records were shown on the first page, so on and so forth.
To create navigation for the paginated data, you want to find out how many records are in your result set, which can be done through the count($array) function of PHP. Then, to find the number of pages, simply use something like:
$numPages = ceil(count($array)/$recordsPerPage);
Where $array is your dataset from the SQL query. The ceil() function rounds the result up to the next integer.
Once you have this result, you simply need to output links to each page, which can be done simply with a for loop:
for($i = 0; i < $numPages; i++)
{
echo '<a href="/search.php?page="' . $i+1 . '>' . $i+1 . '</a>';
}
To create first, previous, next and last page links, you need to do something like:
$firstPage = 1;
$previousPage = $currentPage - 1; // you may want to check here or elsewhere to make sure you have no page zero
$nextPage = $currentPage + 1; // may also want to make sure you don't go past the last page
$lastPage = $numPages;
These values can then be put into your generated links.
Again, I will refer you to Luc M's comment... These need to be fixed, take a look at mysqli functions instead of the now-deprecated mysql_*() functions you're currently using, make sure you clean any user-inputted data before using it, and consider looking at the MVC design pattern.
Hopefully, this will help you out.

Categories