This only returns the last one of my rows:
<?php
function all_infos_query() {
global $connection;
$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "JOIN subjects ";
$query .= "ON pages.subject_id=subjects.id";
$infos_set = mysqli_query($connection, $query);
confirm_query($infos_set);
return $infos_set;
}
function infos_content() {
$infos_set = all_infos_query();
while($info = mysqli_fetch_assoc($infos_set)) {
$output = htmlentities($info["content"]);
$output .= " <br><br>";
}
mysqli_free_result($infos_set);
return $output;
}
?>
<?php echo infos_content() ?>
If I echo it like this it works (returns all rows):
<?php
$result = all_infos_query();
if($result === FALSE) {
echo "query failed: " . mysqli_error($connection);
}
else {
while($row = mysqli_fetch_array($result)) {
echo htmlentities($row['content']);
echo "<br><br>";
}
}
?>
What do I have to change in the function infos_content() to also get all the rows?
Thanks a lot!
This is because you redefine $ouput for every result
while($info = mysqli_fetch_assoc($infos_set)) {
$output = htmlentities($info["content"]);
$output .= " <br><br>";
Instead, create $ouput outside the loop and append to it..
$output ='';
while($info = mysqli_fetch_assoc($infos_set)) {
$output .= htmlentities($info["content"]);
$output .= " <br><br>";
Related
I was wondering if anyone could help with a conceptual issue I'm having, or if there is a better way.
Basically I am searching my database for an array of terms through a search bar.
I have a function that loops through each term and then uses that for a search. It puts everything in an array and returns the array that is then processed into a table.
The search works fine, I put in the terms and it loops through them pushing the rows into an array. Now because I am pushing into different Arrays, the parent Array I Have has indexed keys, I want to change that to be keys of the terms and in the array there are two other arrays 1 for the number of results and another for the results.
// Search index php
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="search">
<form id= "search" action="searchresults.php" method="POST">
<input type="text" name="txtsearch" size="30" id="txtsearch">
<input type="submit" name="srchbtn" id="srchbtn">Search</button>
</form>
</body>
</html>
//Search PHP
<?php
include_once "iud.php";
$arrayval = array();
if(isset($_POST['txtsearch'])){
$search=$_POST['txtsearch'];
}else{
$search = '';
}
$search1 = explode(" ", $search);
array_push($arrayval, $search1);
$combined = array();
foreach ($arrayval as $val){
$orIndex = checkOr($val);
if(empty($orIndex)){
$valcntr = count($val);
$results = getResults($val);
print_r($results);
}
}
function getResults($array){
include_once "iud.php";
$db = connectDatabase();
$totalResults = array();
$length = count($array);
for ($i = 0; $i < $length; $i++){
$outputDisplay = "";
$myrowcount = 0;
$sql_statement = "SELECT userid, username, firstname, lastname ";
//, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes ";
$sql_statement .= "FROM userlist ";
$sql_statement .= "WHERE (firstname LIKE '%$array[$i]%' or lastname LIKE '%$array[$i]%')";
$sql_statement .= "ORDER BY lastname, firstname";
$sqlResults = selectResults($db, $sql_statement);
$error_or_rows = $sqlResults['resultNum'];
if (substr($error_or_rows, 0 , 5) == 'ERROR')
{
$outputDisplay .= "<br />Error on DB";
$outputDisplay .= $error_or_rows;
} else {
array_push($totalResults, $sqlResults);
$arraySize = $error_or_rows;
}
}
return ($totalResults);
}
function buildTable($totalResults){
include_once "iud.php";
$outputDisplay = "";
$outputDisplay .= '<div id="resultstable">';
$outputDisplay .= '<ul id="results">';
$myrowcount = 0;
for ($i=0; $i < count($totalResults); $i++)
{
$myrowcount++;
$contactid = $totalResults[$i]['userid'];
$firstname = $totalResults[$i]['firstname'];
$lastname = $totalResults[$i]['lastname'];
$pcat = $totalResults[$i]['username'];
$outputDisplay .= '<li id='.$contactid.' class="indRes" ';
$outputDisplay .= 'name="'.$contactid.'" >';
$outputDisplay .= '<span style="font-size:10px;cursor:pointer" onclick="getContactsToForm();">';
$outputDisplay .= '<h3>'.$firstname.' ' .$lastname. '</h3>';
$outputDisplay .= '</span>';
$outputDisplay .= '</li>';
}
$outputDisplay .= '</ul>';
$outputDisplay .= "</div>";
return $outputDisplay;
}
function checkOr($searchArray){
if (in_array("OR",$searchArray)){
$orPos = array_search("OR", $searchArray);
if (!empty($orPos)){
$surrVal = "";
$surrVal = --$orPos;
$orValArray = array();
array_push($orValArray,$searchArray[$surrVal]);
$surrVal = $orPos+2;
array_push($orValArray,$searchArray[$surrVal]);
return $orValArray;
}
}
}
?>
//common functinos IUD
<?php
function connectDatabase()
{
$db = mysqli_connect('localhost','root','');
if (!$db)
{
print "<h1>Unable to Connect to mysqli</h1>";
}
$dbname = 'test';
$btest = mysqli_select_db($db, $dbname);
if (!$btest)
{
print "<h1>Unable to Select the Database</h1>";
}
return $db;
}
function selectResults($db, $statement)
{
$output = "";
$outputArray = array();
$db = connectDatabase();
if ($db)
{
$result = mysqli_query($db, $statement);
if (!$result) {
$output .= "ERROR";
$output .= "<br /><font color=red>mysqli No: ".mysqli_errno();
$output .= "<br />mysqli Error: ".mysqli_error();
$output .= "<br />SQL Statement: ".$statement;
$output .= "<br />mysqli Affected Rows: ".mysqli_affected_rows()."</font><br />";
array_push($outputArray, $output);
} else {
$numresults = mysqli_num_rows($result);
$outputArray['resultNum'] = $numresults;
for ($i = 0; $i < $numresults; $i++)
{
$row = mysqli_fetch_array($result);
$outputArray["rowArray"] = $row;
}
}
} else {
array_push($outputArray, 'ERROR-No DB Connection');
}
return $outputArray;
}
function iduResults($db, $statement)
{
$output = "";
$outputArray = array();
$db = connectDatabase();
if ($db)
{
$result = mysqli_query($db, $statement);
if (!$result) {
$output .= "ERROR";
$output .= "<br /><font color=red>mysqli No: ".mysqli_errno();
$output .= "<br />mysqli Error: ".mysqli_error();
$output .= "<br />SQL Statement: ".$statement;
$output .= "<br />mysqli Affected Rows: ".mysqli_affected_rows()."</font><br />";
} else {
$output = mysqli_affected_rows();
}
} else {
$output = 'ERROR-No DB Connection';
}
return $output;
}
?>
My search returns an array that when printed looks like this:
Array(
[0]=>Array
(
[resultNum]=>1
[rowArray]=>Array(
[0]=>1
[userid]=>1
etc
)
)
[1]=>Array
(
[resultNum]=>1
[rowArray]=>Array(
[0]=>2
[userid]=>2
etc
)
)
I want to make the two outer arrays' keys [0],[1] into the search terms that are used in the loop through the getResults($array) function.
Any ideas?
Change
array_push($totalResults, $sqlResults);
to:
$totalResults[$array[$i]] = $sqlResults;
to make it an associative array instead of an indexed array.
P.S. you should learn to use foreach to loop over array elements, and use prepared statements to prevent SQL injection.
Also, selectResults() is only returning the last row of the query. It should be:
} else {
$numresults = mysqli_num_rows($result);
$outputArray['resultNum'] = $numresults;
$outputArray['rowArray'] = array();
for ($i = 0; $i < $numresults; $i++)
{
$row = mysqli_fetch_array($result);
array_push($outputArray["rowArray"], $row);
}
so that it returns all the rows instead of overwriting rowArray each time through the loop.
i have little problem here, i want to generate some data to specific JSON format from Mysql using PHP, this is my PHP code
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
// echo(json_encode($names));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
?>
With this code, the result was
[
[1478616679000, 1478616677000, 1478616675000, 1478616673000, 1478616671000],
[28.4126, 28.5361, 28.4126, 28.4126, 28.2891]
]
Yes, that is valid JSON but, i want to use this JSON for chart in highcharts.com, so i need the JSON format like this
[
[1257811200000, 29.00],
[1257897600000, 29.04],
[1257984000000, 28.86],
[1258070400000, 29.21],
[1258329600000, 29.52],
[1258416000000, 29.57],
[1258502400000, 29.42],
[1258588800000, 28.64],
[1258675200000, 28.56],
[1258934400000, 29.41],
[1259020800000, 29.21],
[1259107200000, 29.17],
[1259280000000, 28.66],
[1259539200000, 28.56]
]
Gladly if someone can help me, i'm stuck for a days try to solving this issue
If you want the code like that, you must fix the code:
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
must be something like this:
while($row = $result->fetch_array()){
$rows[] = array(
(float)$row['ai0_hist_value'],
strtotime($row['meas_date'])*1000);
}
echo (json_encode($rows));
You were saving in $data2 an array with two arrays, the text and the data. You must save a row for each pair of 'text' and 'data'.
Could construct the formatted series data to begin with like below:
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$seriesData[] = [ strtotime($row['meas_date'])*1000, (float)$row['ai0_hist_value'] ];
}
echo (json_encode($seriesData));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
This will generate the array you want, there is no need to do all that fiddling with the data from the database
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
$rows = array();
if ($result = $db->query($sql)) {
while($row = $result->fetch_array()){
$rows[] = array(strtotime($row['meas_date'])*1000,
$row['ai0_hist_value']
);
}
}
echo json_encode($rows);
Now you will need to convert the text to float in the javascript. This is because JSON is passed as text and not any other data type, so it has to be converted, if necessary in the receiving javascript.
I need to get variable code from URL so I $codes = $_GET['code']; (url example website.com/update?code[]=7291&code[]=9274&code[]=8264&) then I SELECT firstname FROM guests WHERE invitecode = $codes" then I output data and set as $relatives = $row["firstname"] and then later on in the file I need to echo/print print $relative.
Why is this not working for me?
... connection made ...
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE invitecode = $codes";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
Update:
So now using:
<?php
$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
$thecodes .= (int)$vals . ",";
if($thecodes != "")
{
$thecodes = trim($thecodes, ",");
$sql = "SELECT firstname FROM guests WHERE invitecode IN ($thecodes)";
$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
}
else
{
}
?>
It works but I would like to enter the foreach ($relatives as $relative) { echo $relative; }; into a value like this $message = $firstname . " " . $lastname . " will be coming to your event. " . ;.
In the end it would turn out something like this: $message = $firstname . " " . $lastname . " will be coming to your event. " . foreach ($relatives as $relative) { echo $relative . " "; };.
For some reason it won't work when I combine them.
Use the IN operator for this.
<?php
$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
$thecodes .= (int)$vals . ","; //Loop through making sure each is an int for security reasons (No sqli)
if($thecodes != "") //There is at least one code
{
$thecodes = trim($thecodes, ","); //Remove any additional commas
$sql = "SELECT firstname, lastname FROM guests WHERE invitecode IN ($thecodes)"; //Use the IN operator
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row["firstname"] . " " . $row["lastname"] . "is coming to your event";
}
}
}
else //No codes to be queried
{
}
?>
Can this be a solution for you?
$relatives = array(); // declare array
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE ";
foreach ($codes as $code) $sql .= "invitecode = " . intval($code) . " OR ";
$sql .= "1=2"; // simple way to remove last OR or to make sql valid if there are no codes
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
array_push($relatives, $row["firstname"]);
}
}
foreach ($relatives as $relative) {
print $relative;
}
I think this will work...
... connection made ...
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE invitecode = '$codes'";
$result = mysqli_query($conn, $sql) or die('-1' . mysqli_error());
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo ($row['firstname']);
}
}
I have been asked to revise an existing site, it's still using PHP5.3 and an old version of PHPmyDirectory, and the code is a little messy.
I'm trying to revise it to just display the list of cities in two columns. I'm trying to do it as a table, as it seemed easiest, but I could also just pull the results into to side by side divs, as there are never more than 26 cities listed (so first half or first 13 in div one, the rest in div two).
Here's the existing original code (I know its not mysqli, but we'll be redoing this site shortly so there's no sense trying to redo a million pages of code right now):
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
return $output;
}
This is what is looks like currently: Current Site
Here's what I've tried to do:
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$result_array = array();
while ($service = fetch_array($result)) {
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2) {
break;
}
else {
while ($service2 = fetch_array($result2)) {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
echo "<table>";
for ($j=0; $j<$i; $j=$j+2) {
echo "<tr>";
echo "<td>".$title_array[$j]."</td><td>".$title_array[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<p><b>".$title." will travel for an additional fee!</b></p>";
}
else {
$output .="";
}
}
return $output;
}
And here's what I'm getting: DEV site
I'm very much a PHP newbie, and my understanding is pretty spotty, but I've tried a bunch of different solutions I've found here, and can't get them to work. I'm sure I'm missing something obvious.
Thanks for any pointers!
if I got it correct you should change your
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
with
else {
$output = "<table>";
$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "";
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<tr><td>'."{$service2['title']}".'</td>';
$even_odd=false;
} else {
$output .= '<td>'."{$service2['title']}".'</td></tr>';
$even_odd=true;
}
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
if (!$even_odd)$output .="<td></td></tr>";
$output .="</table>";
}
}
Try this, I couldn't test it of course, since I've got no access to the data being loaded.
echo "<table>";
$result_array = array();
while ($service = fetch_array($result))
{
//this will loop multiple times. 7 times for Tony S. in the example.
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2)
{
break;
}
else
{
while ($service2 = fetch_array($result2))
{
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
}
}
for ($j=0; $j < count($result_array); $j++)
{
if ($j % 2 == 0)
{
echo "<tr>";
}
echo "<td>".$result_array[$j][0]." (".$result_array[$j][1].")</td>";
if ($j % 2 == 0)
{
echo "</tr>";
}
if ($j % 2 == 1 && $j == count($result_array)-1)
{
echo "<td></td></tr>";
}
}
echo "</table>";
Paste and replace between this lines:
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
.... PASTE IN HERE ....
}
Building on Kim's code, I was able to get it working with some revisions. I also scrapped the table for divs, since it seems less messy to me and it seemed like the table styling was interfering somehow.
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
} else {
$output = "<div>";
//$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<div style="float:left;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=false;
} else {
$output .= '<div style="float:right;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=true;
}
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<div style='clear:both;width:90%;float:none;'><p><b>".$title." will travel for an additional fee!</b></p></div>";
} else {
}
}
return $output;
}
Thanks so much Kim and Mouser!
I decided to give PHP a try, and then bought lynda.com's essential training tutorial.
The problem is, that I get this error:
( ! ) Notice: Uninitialized string offset: 0 in
C:\wamp\www\widget_corp\includes\functions.php on line 147.
when trying to compare two values.
Can anyone help me ? :)
error in navigation function:
if($page["id"] == $selectedPage['id']){
Class content.php below:
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php");?>
<?php findSelectedPage(); ?>
<?php include("includes/header.php");?>
<table id="structure">
<tr>
<td id="navigation">
<?php echo navigation($selSubject, $selectedPage);?>
<br/>
+ Add a new subject
</td>
<td id="page">
<?php echo checkSubjOrPage();?>
<br/>
<div id="footer">Copyright 2007, Widget Corp</div>
</td>
</tr>
</table>
<?php require("includes/footer.php"); ?>
class function.php below:
<?php
//This file is the place to store all basic functions.
//NB!
//function to prevent problems with submitting values, that contains
//chars such as: "", '' etc., into the database.
function mysql_prep($value){
$magic_quotes_active = get_magic_quotes_gpc;
//i.e. php>= v4.3.0
$new_enough_php = function_exists("mysql_real_escape_string");
if($new_enough_php){
//undo any magic quotes effects so mysql_real_escape_string can do the work
if($magic_quotes_active){
$value = stripslashes($value);
}
$value = mysql_real_escape_string($value);
} else { // before PHP v4.3.0
//if magic quotes aren't already on then add slashed manually
if(!$magic_quotes_active){
$value = addslashes($value);
}
}
return $value;
}
function confirm_query($result_set){
if(!$result_set){
die("Database connection failed: " . mysql_error());
}
}
function getAllSubjects(){
global $connection;
$query = "SELECT *
FROM subjects
ORDER BY position ASC";
$subject_set = mysql_query($query, $connection);
confirm_query($subject_set);
return $subject_set;
}
function getPagesForSubject($subject_id){
global $connection;
$query = "SELECT *
FROM pages
WHERE subject_id = {$subject_id}
ORDER BY position ASC";
$page_set = mysql_query($query, $connection);
confirm_query($page_set);
return $page_set;
}
function get_subject_by_id($subject_id){
global $connection;
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE id=" . $subject_id . " ";
$query .= "LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
//REMEMBER:
//if no rows are returned, fetch_array will return false.
if($subject = mysql_fetch_array($result_set)){
return $subject;
} else {
return NULL;
}
}
function get_page_by_id($page_id){
global $connection;
$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "WHERE id=" . $page_id . " ";
$query .= "LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
//REMEMBER:
//if no rows are returned, fetch_array will return false.
if($page = mysql_fetch_array($result_set)){
return $page;
} else {
return NULL;
}
}
function checkSubjOrPage(){
global $selSubject;
global $selectedPage;
if(!is_null($selSubject)){
return "<h2>" . $selSubject['menu_name'] . "</h2>";
} else if(!is_null($selectedPage)){
return "<h2>" . $selectedPage['menu_name'] . "</h2>" . "<div>" . $selectedPage['content'] . "</div>";
} else {
return "<h2>" . "Select a subject or page to edit!" . "</h2>";
}
}
function findSelectedPage(){
global $selSubject;
global $selectedPage;
if(isset($_GET['subj'])){
$selSubject = get_subject_by_id($_GET['subj']);
$selectedPage = "";
} else if(isset($_GET['page'])){
$selSubject = NULL;
$selectedPage = get_page_by_id($_GET['page']);
} else {
$selectedPage = NULL;
$selSubject = NULL;
}
}
function navigation($selSubject, $selectedPage){
$output = "<ul class=\"subjects\">";
//3. Perform our database query
$subject_set = getAllSubjects();
while($subject = mysql_fetch_array($subject_set)){
$output .= "<li";
if($subject["id"] == $selSubject['id']){
$output .= " class=\"selected\"";
}
$output .= "><a href=\"content.php?subj=" . urlencode($subject["id"]) .
"\">{$subject["menu_name"]}</a></li>";
$page_set = getPagesForSubject($subject["id"]);
$output .= "<ul class=\"pages\">";
while($page = mysql_fetch_array($page_set)){
$output .= "<li";
if($page["id"] == $selectedPage['id']){
$output .= " class=\"selected\"";
}
$output .= "><a href=\"content.php?page=" . urlencode($page{"id"}) .
"\">{$page["menu_name"]}</a></li>";
}
$output .= "</ul>";
}
$output .= "</ul>";
return $output;
}
function getPositions(){
$subject_set = getAllSubjects();
$subject_counts = mysql_num_rows($subject_set);
$output = "<select name=\"position\">";
//$subject_counts + 1 b/c we are adding a subject.
for($count = 1; $count <= $subject_counts +1; $count++){
$output .= "<option value=\"{$count}\">{$count}</option>";
}
return $output . " </select>";
}
?>
here you override $selectedPage to a string or set it to null
function findSelectedPage(){
global $selSubject;
global $selectedPage;
if(isset($_GET['subj'])){
$selSubject = get_subject_by_id($_GET['subj']);
$selectedPage = "";
} else if(isset($_GET['page'])){
$selSubject = NULL;
$selectedPage = get_page_by_id($_GET['page']);
} else {
$selectedPage = NULL;
$selSubject = NULL;
}
}
And here it should be an array:
if($page["id"] == $selectedPage['id']){
function findSelectedPage(){
global $selSubject;
global $selectedPage;
if(isset($_GET['subj'])){
$selSubject = get_subject_by_id($_GET['subj']);
$selectedPage = NULL;
} else if(isset($_GET['page'])){
$selSubject = NULL;
$selectedPage = get_page_by_id($_GET['page']);
} else {
$selectedPage = NULL;
$selSubject = NULL;
}
}
function navigation($selSubject, $selectedPage){
$output = "<ul class=\"subjects\">";
//3. Perform our database query
$subject_set = getAllSubjects();
while($subject = mysql_fetch_array($subject_set)){
$output .= "<li";
if(isset($selSubject['id']) && $subject["id"] == $selSubject['id']){
$output .= " class=\"selected\"";
}
$output .= "><a href=\"content.php?subj=" . urlencode($subject["id"]) .
"\">{$subject["menu_name"]}</a></li>";
$page_set = getPagesForSubject($subject["id"]);
$output .= "<ul class=\"pages\">";
while($page = mysql_fetch_array($page_set)){
$output .= "<li";
if(isset($selectedPage['id']) && $page["id"] == $selectedPage['id']){
$output .= " class=\"selected\"";
}
$output .= "><a href=\"content.php?page=" . urlencode($page{"id"}) .
"\">{$page["menu_name"]}</a></li>";
}
$output .= "</ul>";
}
$output .= "</ul>";
return $output;
}