Passing session variables to another page - php

I am trying to pass session variable to the next page, index.php but i have gotten an error undefined index on foreach($_SESSION['result'] as $row). May i know what's wrong?
<?php
session_start();
$search = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search = $db->real_escape_string($search);
if (strlen($search) >= 1 && $search !== ' ') {
$query = 'SELECT * FROM tablename WHERE name LIKE "%'.$search.'%"';
$result = $db->query($query) or trigger_error($db->error."[$query]");
while($results = $result->fetch_array()) {
$resultArray[] = $results;
}
if (isset($resultArray)) {
foreach ($resultArray as $result) {
$show_name = preg_replace("/".$search."/i", "<b class='highlight'>".$search."</b>", $result['name']);
$show_url = 'index.php';
$out = str_replace('name', $show_name, $html);
$out = str_replace('url', $show_url, $out);
$_SESSION['result']= $result['name'];
echo($out);
}
}
}
?>
index.php
session_start();
<table>
<?php foreach($_SESSION['result'] as $row){ ?>
<tr>
<td>
<?php echo $row['name'];?>
</td>
<td>
<?php echo $row['description'];?>
</td>
</tr>
<?php } ?>
</table>

if $_SESSION['result'] is an array then try like below
$_SESSION['result'][]= $result['name'];
as per your code session result variable is not an array

You never start the session in the first file. Start the file with
<?php
session_start();
Because you're missing that, when you assign a value to $_SESSION['result'] after your queries, nothing is saved in session.
There is another error. You mean for $_SESSION['result'] to be an array, but you're saving it as a string. Change:
$_SESSION['result']= $result['name'];
To
$_SESSION['result'][]= $result['name'];

Related

How can I change the id of an SQL query automatically via PHP?

I'm creating a news website, and when I create a new article, the title/text are registered on the database. The articles are in a dynamic PHP page with header/footer, with the text itself being called from the database . On the index there is a list with links to every article, and I want those links to change the id automatically.
index.php
<?php include "header.php"; session_start();?>
<?php include "slideshow.php"; ?>
<?php include "db.php"; ?>
<br>
<table class="table_index">
<?php
while ($line = mysqli_fetch_array($query)) {
echo '<tr><td class="td_tit"><a href="example_article.php" >'.$line["title_article"].'</a></td></tr>';
echo '<tr><td class="td_subt"><a href="example_article.php" >'.$line["subtitle_article"].'</a></td></tr>';
$_SESSION['id_article'] = $line["id_tb_article"];
}
?>
</table>
<?php include "footer.php"; ?>
example_article.php
<?php
session_start();
include "header.php";
$id_article = $_SESSION['id_article'];
$query = "SELECT title_article, subtitle_article, content_article FROM tb_article WHERE id_tb_article = $id_article";
$conn = mysqli_connect('127.0.0.1:3307', 'root', '', 'article') or die("error");
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div class='titlediv'><h1 class='title'>" . $row["title_article"]. "</h1></div><div class='titlediv'><h3 class='title'>". $row["subtitle_article"]. "</h3></div><div class='textdiv'><p class='text'>" . $row["content_article"]. "</p></div><br>";
}
} else {
echo "0 results";
}
include "footer.php";
?>
You shouldn't use session parameters for this task. Instead use get parameters (or post) here is a little example. Also your code is vulnerable to SQL-Injection, but thats your problem :D
Index.php rewrite your while loop like this
while ($line = mysqli_fetch_array($query)) {
echo '<tr><td class="td_tit">'.$line["title_article"].'</td></tr>';
echo '<tr><td class="td_subt">'.$line["subtitle_article"].'</td></tr>';
}
then fetch the id in example_article.php like this:
$id_article = $_GET['id_article'];

PHP MySQL display data by id from database - freedom placement

I would like to have the freedom to place a row entry from my database wherever i' prefer in the page. Right now, the php code that I use is as follows (it is clean working code):
<html><head></head>
<body>
<?php
$db = mysql_connect("xxx","xxx","xxx") or die("Database Error");
mysql_select_db("caisafety",$db);
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `cert_rr` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
echo $row['id']; while($row = mysql_fetch_array( $result )) {
echo "<br><br>";
echo $row['basic3'];
echo $row['basic2'];
echo $row['basic1'];
}
?>
</body>
</html>
I call id through the browser Eg. http://site.com/getid.php?id=10 . But I do not have the freedom to place my row entry within my html. For eg. like this:
<table><tr>
<td align="center">BASIC INFO 1: <?php echo $row['basic1']; ?></td>
<td align="center">BASIC INFO 2: <?php echo $row['basic2']; ?></td>
</tr></table>
I can place html within echo PHP tags but then I have to clean up my html and thats a lot of work. Retaining HTML formatting would be preferred. Any help or guidelines on this would be much appreciated.
<?php
$db = mysql_connect("xxx","xxx","xxx") or die("Database Error");
mysql_select_db("caisafety",$db);
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `cert_rr` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
//you need to retrieve every row and save to an array for later access
for($rows = array(); $tmp = mysql_fetch_array($result);)
{
$rows[] = $tmp;
}
//now you can use the $rows array where every you want e.g. with the code from Zhube
?>
....
<table><?php foreach($rows as $r):
<td><?php echo $r['id'] ?></td><?php endforeach ?>
</table>
By
while($row = mysql_fetch_array( $result )) {
echo "<br><br>";
echo $row['basic3'];
echo $row['basic2'];
echo $row['basic1'];
}
you save only the last row
Instead of having your HTML tags as part of the PHP variable, do something like this instead:
<table><?php foreach($row as $r):?>
<td><?php echo $r['id'] ?></td><?php endforeach ?>
</table>

PHP MySQL undefined Index and other errors

having trouble getting a script of mine to run correctly, I have 2 undefined index errors and an invalid argument supplied error that for the life of me I can't figure out why I'm getting. the 2 undefined index errors come from these lines.
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
and
if (!is_null($_GET['page']))
and my invalid argument error is this
Warning: Invalid argument supplied for foreach() in
generated from this
<?php foreach ($books as $book) : ?>
my full code between the two classes is this.. any ideas of what I've done wrong? tearing my hair out over this.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Catalog</title>
</head>
<body bgcolor="white">
<?php
/////////////////////////////////////////////////
//connect to db
/////////////////////////////////////////////////
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
if(!is_null($_GET['order']) && $_GET['order'] != 'courseTitle')
{
$thesort = $_GET['order'];
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY ".$_GET['order'];
}
else
{
$thesort = "courseTitle";
$query = "Select * FROM book
INNER JOIN course
ON book.course = course.courseID
ORDER BY $thesort";
}
//if page is null go to first page otherwise query for correct page
if (!is_null($_GET['page']))
{
$query = $query." LIMIT ".($_GET['page']*8-8).", 8";
}
else
{
$query = $query." LIMIT 0, 8";
}
//query result
$books = $db->query($query);
//get number of overall rows
$query2 = $db->query("SELECT * FROM book");
$count = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$count = $count->fetch();
$count = $count['totalRecords'];
?>
<table border =" 1">
<tr>
<th bgcolor="#6495ed"><a href="?order=course">Course #</th>
<th bgcolor="#6495ed"><a href="?order=courseTitle">Course Title</th>
<th bgcolor="#6495ed"><a href="?order=bookTitle">Book Title</th>
<th bgcolor="#6495ed"></th>
<th bgcolor="#6495ed"><a href="?order=price">Price</th>
</tr>
<?php foreach ($books as $book) : ?>
<tr>
<td><?php echo $book['course']; ?></td>
<td><?php echo $book['courseTitle']; ?></td>
<td><?php echo $book['bookTitle']; ?></td>
<td><?php
$bookcourse = $book['course'];
$isbn = $book['isbn13'];
$booklink = "<a href=\"course.php?course=$bookcourse&isbn=$isbn\">";
echo $booklink ;?><img src='images/<?php echo $book['isbn13'].'.jpg'; ?>'></a></td>
<td><?php echo $book['price']; ?></td>
</tr>
<?php endforeach; ?>
</tr>
</table>
<?php
//paging function... not sure if it works correctly?
for ($j=1; $j <= ceil($count/8); $j++)
{ ?>
<a href=<?php echo "?page=".$j."&order=".$thesort; ?>><?php echo $j; ?></a>
<?php
}?>
</body>
</html>
**course.php**
<?php
//get data from index.php
$course = $_GET['course'];
$isbn = $_GET['isbn'];
//connect to db
$dsn = 'mysql:host=localhost;dbname=book_catalog';
$username = "php";
$password = "php";
$db = new PDO($dsn, $username, $password);
//get data
$query = "Select * FROM book, course, author, publisher
WHERE book.isbn13 = $isbn AND book.course = '$course' AND book.course = course.courseID AND book.bookID = author.bookID AND book.publisher = publisher.publisherID
ORDER BY book.bookID";
//query results
$books = $db->query($query);
//error troubleshooting
if (!$books) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
//count the number of rows in the result
$results = $books->fetchAll();
$rowCount = count($book);
//get data from results
foreach($results as $book){
$bookID = $book['bookID'];
$bookTitle = $book['bookTitle'];
$isbn = $book['isbn13'];
$price = $book['price'];
$desc = $book['description'];
$publisher = $book['publisher'];
$courseTitle = $book['courseTitle'];
$courseID = $book['courseID'];
$credits = $book['credit'];
$edition = $book['edition'];
$publishDate = $book['publishDate'];
$length = $book['length'];
$firstName = $book['firstName'];
$lastName = $book['lastName'];
}
if($numrows > 1)
{
foreach ($books as $book)
{
$authorArray[] = $book['firstName'] + ' ' + $book['lastName'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CIS Department Book Catalog</title>
</head>
<body bgcolor=white">
<table border="0">
<tr>
<td>
<img src='images/<?php echo $isbn.'.jpg'; ?>'>
</td>
<td>
<?php
echo "For Course: $courseID $courseTitle ($credits)";
echo "</br>";
echo "Book Title: $bookTitle";
echo "</br>";
echo "Price: $price";
echo "</br>";
echo "Author";
if ($numResults > 1)
{
echo "s:";
for ($i = 0; $i < $numResults; $i++)
{
if ($i!=0)
echo ", $authorArray[i]";
else
echo $authorArrat[i];
}
}
else
echo ": $firstName, $lastName";
echo "</br>";
echo "Publisher: $publisher";
echo "</br>";
echo "Edition: $edition ($publishDate)";
echo "</br>";
echo "Length: $length pages";
echo "</br>";
echo "ISBN-13: $isbn";
?>
</td>
</tr>
<tr>
<td colspan="2">
<?php echo "Description: $desc"; ?>
</td>
</tr>
</table>
</body>
</html>
You should be using isset not is_null to keep it from warning about undefined variables.
$books is never defined It was defined, just incorrectly ... foreach needs it to be an array. You really don't need it anyway, fetch each row into the array with a while loop. (see my example below). You're also redefining $count several times in your query.
And like #Brad said. Use prepared statements and placeholders. Your database will end up hacked with your current code.
EDIT
Answer to your question. query() returns a statement handle. (I've defined it as $sth). fetch() returns a result which you need to pass one of the fetch mode constants (or define it by default earlier with $db->setFetchMode())
To get the books you need to have
$books = array();
$sth = $db->query($query);
while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) {
$books[] = $row; // appends each row to the array
}
Here's how your code should look to get a count.
// you're not using the $query2 you defined ... just remove it
$sth = $db->query("SELECT Count(*) As 'totalRecords' FROM book");
$result = $sth->fetch(PDO::FETCH_ASSOC);
$count = $result['totalRecords'];
Take a look at:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers Looks like a good guide to give you an in-depth understanding of how to use PDO. Pay special attention to error handling and to prepared statements!

Display only one entry from the database with PHP

The following code retrieves and displays the correct data from the database however it gets all the data. I need a way to assign each value it retrieves from the database to a PHP variable. For example, if it gets "Joe", "Henry", and "Robert" from the database, I'd like one variable for each of those and right now it returns and array with all the values.
<?php
dbCon();
$query1 = mysql_query("SELECT * FROM hosts WHERE name!=''");
while($row1 = mysql_fetch_assoc($query1)) {
$res = $row1['name'] . '<br />';
echo $res;
}
?>
<?php
function echoName($id) {
dbCon();
$query1 = mysql_query("SELECT * FROM hosts WHERE id='$id'");
while($row1 = mysql_fetch_assoc($query1)) {
$res = $row1['name'] . '<br />';
echo $res;
}
}
?>
<div id="joe_div">
<?
echoName("1");
?>
</div>
.....
<div id="henry_div">
<?
echoName("2");
?>
</div>
Declare variable variables as such:
while($row1 = mysql_fetch_assoc($query1)) {
$$row1['name'] = $row1['name']
}
echo $Joe; //returns Joe
Though I don't know why you would ever need that
if it gets "Joe", "Henry", and "Robert" from the database, I'd like one variable for each of those
So try this:
<?php
dbCon();
$query1 = mysql_query("SELECT * FROM hosts WHERE name!=''");
while($row1 = mysql_fetch_assoc($query1)) {
$$row1['name'] = $row1['name'];
}
echo $Joe;
echo $Henry;
echo $Robert;
?>
P.S: I don't know why you want to do this, but i am sure you have a better approach to solve your problem.

Know if the record has been displayed 3 records and if so then put the another 3 records in a new line

Ok I have this code:
<?
$name=$_POST['name'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE id='$name'");
$ss = ""
while($row = mysql_fetch_array($result))
{
$ss .= "<div style='border:1px solid red; float:left; width:100px;'><img src="Images/media'.$row['name'].'" />";
$ss .= "<p>".$row['title']."</p>";
$ss .= "<p>".$row['description']."</p>";
$ss .= "<a href='".$row['link']."'>".$row['link']."</a></div>";
}
mysql_close($con);
?>
<? echo $ss; ?>
Now, I want to organize the display, therefore, I want the record to be set by 3 but the only problem where im stuck is I dont know how to make it to display in by set of 3. Im open for a suggestion, please help me. Thank you.
a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
a code
mysql_connect("localhost","root","");
mysql_select_db("juliver");
$name = mysql_real_escape_string($_POST['name']);
$data = sqlArr("SELECT * FROM items WHERE id='$name'");
$data = array_chunk($data,3);
include 'template.tpl.php';
a template
<table border='1'>
<? foreach ($data as $row): ?>
<tr>
<? foreach ($row as $cell): ?>
<td><?=$cell['id']?><?=$cell['title']?></td>
<? endforeach ?>
</tr>
<? endforeach ?>
</table>
In while loop you can put the condition to know when it executes 3 times then it would go automatically on other line. have a look
int $a=0;
while($row = mysql_fetch_array($result))
{
if($a%3==0){
this will executes only if when the no of record dividable by 3. means 3,6,9,12..
do this..
}else {
do this..
}
$a++;
}

Categories