I am trying to pass a variable from one page to another using $_GET, and I can't seem to get it to work. I would appreciate any help.
First I create a link based on the results from the database here.
clients.php
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$uid = $auth->SessionUID($_COOKIE['authID']);
$query = $dbh->prepare("SELECT fname, lname, id FROM client WHERE uid=? ORDER by id");
$query->execute(array($uid));
$rslt = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($rslt as $row ){
echo "<a href=../pages/status.php?id=$row[id]>$row[fname]<br></a>";
}
The result from the link are listed on this page
status.php
$cid = $_GET['id'];
$query = $dbh->prepare("SELECT function FROM funcbathing WHERE cid=?");
$query->execute(array($cid));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
if (empty($rslt)){
header('Location: ../views/careplan.php');
echo $cid
}
else{
header('Location: ../views/home.php');
}
I would like to pass the $cid to this page in a text box, but I can't seem to get it work. Here's the page that the id should get passed to.
careplan.php this is a bigger form but I removed the irrelevant information for simplicity.
<input type="text" name="clientid" value="<?php if(isset($_GET['cid'])) { echo $_GET['cid']; } ?>" />
header('Location: ../views/careplan.php?cid='.$cid);
EDIT:
You should learn to print the strings in a valid manor, check error_reporting(E_ALL); and display_errors=on with your string.
then try this:
echo ''.$row["fname"].'<br>';
or:
echo sprintf('%s<br>', $row['id'], $row['fname']);
or even:
echo "{$row["fname"]}<br>";
or any of the other hundreds way to write a valid string
Related
I'm having a problem getting a result from my mysql database and getting it to popular a form. Basically, i'm making an item database where players can submit item details from a game and view the database to get information for each item. I have everything working as far as adding the items to the database and viewing the database. Now i'm trying to code an edit item page. I've basically reused my form from the additem page so it is showing the same form. At the top of my edititem page, I have the php code to pull the item number from the url as the item numbers are unique. So i'm using a prepared statement to pull the item number, then trying to retrieve the rest of the information from the database, then setting each information to a variable. Something is going on with my code but I can't find any errors. I entered a few header calls to debug by putting information in the url bar...But the headers aren't even being called in certain spots and im not getting any errors.
In the form, I used things like
<input name="itemname" type="text" value="<?php $edit_itemname?>">
and nothing is showing in the textbox. I'm fairly new to php and it seems much more difficult to debug than the other languages i've worked with..Any help or suggestions as far as debugging would be greatly appreciated. I posted my php code below as well if you guys see anything wrong...I shouldn't be having issues this simple! I'm pulling my hair out lol.
Thanks guys!
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
}else{
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
}else{
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
}else{
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
header("Location: edititem.php?testing");
}
}
}
}
?>
To get the value of $edit_itemname into the output you should be using <?= not <?php. Saying <?php will run the code, so basically that is just a line with the variable in it. You are not telling it to print the value in the variable.
If your whole line looks like:
<input name="itemname" type="text" value="<?= $edit_itemname?>">
That should give you what you are looking for. The <?= is the equivalent of saying echo $edit_itemname;
If you don't like using <?= you could alternatively say
<input name="itemname" type="text" value="<?php echo $edit_itemname; ?>">
Your code should be change to a more readable form and you should add an output - I wouldn't recomment to use <?= - and you need to choose what you're going to do with your rows - maybe <input>, <table> - or something else?
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
} // no else needed -> exit()
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
} // no else needed -> exit()
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
} // no else needed -> exit()
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
// does not make sense here: header("Location: edititem.php?testing");
// show your data (need to edited):
echo "Name: " + $edit_itemname + "<br/>";
echo "Area: " + $edit_itemarea + "<br/>";
echo "Comment: " + $edit_itemcomments + "<br/>";
// end of current row
echo "<hr><br/>"
}
?>
I want to pass the value of login.php variables $user_key & $user_id to another file statusdata.php for which I have used session. In statusdata.php I want to use those session variable value in sql query of statusdata.php file.
To achieve this in login.php I pass the value of variable $user_key & $user_id to session variable $_SESSION["key"] & $_SESSION["id"] respectively then in statusdata.php I call session variable and pass their value in variable $user_key & $user_id of statusdata.php
Now the problem is when using the variable $user_key & $user_id in SQL query it is not returning proper output but using the same variable in echo it is giving proper value mean session is working fine when I echo the variable but not working in SQL. I have also tried passing the session variable directly but the same thing is happening to work in echo but not in SQL.
login.php
<?php
// Start the session
session_start();
require "conn.php";
$user_key = '8C9333343C6C4222418EDB1D7C9F84D051610526085960A1732C7C3D763FFF64EC7F5220998434C896DDA243AE777D0FB213F36B9B19F7E4A244D5C993B8DFED';
$user_id = '1997';
$mysql_qry = "select * from applications where application_key = '".$user_key."' and application_id like '".$user_id."';";
$result = mysqli_query($conn, $mysql_qry);
if (mysqli_num_rows($result) > 0){
$_SESSION["key"] = ".$user_key.";
$_SESSION["id"] = ".$user_id.";
echo "Login Success";
}
else {
echo "Login Not Success";
}
?>
statusdata.php
<?php
// Start the session
session_start();
require "conn.php";
$user_key = "-1";
if (isset($_SESSION["key"])) {
$user_key = $_SESSION["key"];
}
$user_id = "-1";
if (isset($_SESSION["id"])) {
$user_id = $_SESSION["id"];
}
//creating a query
$stmt = $conn->prepare("SELECT applications.application_id, applications.applicant_name, applications.applicant_aadhaar, applications.applicant_phone, applications.subject, applications.date, applications.description, applications.chairperson_remark, applications.status, officer_accounts.name_of_officer, applications.officer_remark, applications.last_update_on
FROM applications INNER JOIN officer_accounts ON applications.account_id = officer_accounts.account_id
WHERE applications.application_id = '".$user_id."' AND applications.application_key = '".$user_key."';");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result($id, $name, $aadhaar, $phone, $subject, $date, $description, $chairperson, $status, $officername, $officerremark, $lastupdate);
$applications = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['applications.application_id'] = $id;
$temp['applications.applicant_name'] = $name;
$temp['applications.applicant_aadhaar'] = $aadhaar;
$temp['applications.applicant_phone'] = $phone;
$temp['applications.subject'] = $subject;
$temp['applications.date'] = $date;
$temp['applications.description'] = $description;
$temp['applications.chairperson_remark'] = $chairperson;
$temp['applications.status'] = $status;
$temp['officer_accounts.name_of_officer'] = $officername;
$temp['applications.officer_remark'] = $officerremark;
$temp['applications.last_update_on'] = $lastupdate;
array_push($applications, $temp);
}
//displaying the result in json format
echo json_encode($applications);
// Echo session variables that were set on previous page
echo "<br>key is " . $user_key . ".<br>";
echo "id is " . $user_id . ".";
?>
Output login.php
Login Success
Output statusdata.php
[]
key is .8C9333343C6C4222418EDB1D7C9F84D051610526085960A1732C7C3D763FFF64EC7F5220998434C896DDA243AE777D0FB213F36B9B19F7E4A244D5C993B8DFED..
id is .1997..
output I want from statusdata.php (I am getting it if I use direct value in variable $user_key & $user_id not session variable from login.php)
[{"applications.application_id":1997,"applications.applicant_name":"Tanishq","applications.applicant_aadhaar":"987654321","applications.applicant_phone":"123456789","applications.subject":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.date":"2018-07-02 09:11:47","applications.description":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.chairperson_remark":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.status":1,"officer_accounts.name_of_officer":"Chayan Bansal","applications.officer_remark":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.last_update_on":"2018-07-22 09:14:25"}]
key is 8C9333343C6C4222418EDB1D7C9F84D051610526085960A1732C7C3D763FFF64EC7F5220998434C896DDA243AE777D0FB213F36B9B19F7E4A244D5C993B8DFED.
id is 1997.
NOTE: I am taking the output of statusdata.php SQL query in JSON format as in the end I am extracting it in android.
Please help me I have tried everything which other similar questions are suggesting but nothing helps
Looks more like a typo situation. You have this in login.php:
$_SESSION["key"] = ".$user_key.";
$_SESSION["id"] = ".$user_id.";
Which is tainting your original values... by adding needless dots around them. Clean that up by simply assigning as so:
$_SESSION["key"] = $user_key;
$_SESSION["id"] = $user_id;
And it should begin working better.
Side note, you are using prepare, but not using bind_param. Change your SQL prepare to the following (note the ? placeholders), and add bind_param:
$stmt = $conn->prepare("SELECT applications.application_id, applications.applicant_name, applications.applicant_aadhaar, applications.applicant_phone, applications.subject, applications.date, applications.description, applications.chairperson_remark, applications.status, officer_accounts.name_of_officer, applications.officer_remark, applications.last_update_on
FROM applications INNER JOIN officer_accounts ON applications.account_id = officer_accounts.account_id
WHERE applications.application_id = ? AND applications.application_key = ?;");
$stmt->bind_param('ss',$user_id,$user_key);
I am creating a workout logger using PHP and MySQL. The way I have it set up currently, the user uses a select to choose a workout template - and that value is POSTed to the form page. The template name is used to query the database for the names of all the exercises in that template and the number of sets per exercise. The names and sets are put into parallel arrays.
A function is called which generates the form. An element for the template name (ex. Full Body Workout), one for the exercise name (ex. Barbell Deadlift), and one for the set number, with a label/input pair for: weight, reps, rest, and notes.
Screenshot
The increment for the exercise name variable is a counter in $_SESSION, which gets incremented after each successful database insert.
My question is on the logic aspect. How can do I go about incrementing the $_SESSION variable without reseting it back to zero?
session_start();
//User
$user = $_SESSION['email'];
$date = date("Y-m-d");
//Get this script
$thisScript = htmlentities($_SERVER['PHP_SELF']);
//This is the value I want to keep persistent
$_SESSION['nameCount'] = (int)0;
$nameCount = $_SESSION['nameCount'];
//Value from select
$template = $_POST['mySelect'];
//Set log submit button
$logSubmit = $_POST['logSubmit'];
//Check if user is signed in
if ($user) {
if ($template) {
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
//Return query
$result = getResult($template); //Returns result of template
$numRows = getExerciseNum($result);
$exerciseArray = exerciseList($result, $numRows); //Returns set of exercises in template
//For some reason, $result and $numRows is empty after being passed into $exerciseArray
//Reinitialize
$result = getResult($template); //Returns result of template
$numRows = getExerciseNum($result); //numRows
$setsArray = getSets($result, $numRows); //Gets number of sets as array
//Reinitialize
$result = getResult($template); //Returns result of template
$numRows = getExerciseNum($result);
$exerciseIDArray = exerciseIDList($result, $numRows);
//Build form
buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date, $nameCount, $exerciseIDArray);
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} else if (empty($template)){
//Do something if template is empty
require_once("include/connect2db.inc.php");
require_once("include/htmlHead.inc");
echo "<p>Seems the template is empty</p>\n";
echo "<p>Template = $template</p>\n";
//Require Footer
require_once("include/htmlFoot.inc");
mysql_close();
} //End if ($template)
} else if (!isset($user)) {
//If user not logged in
require("include/redirect.php");
}
Here are the relevant functions: Build log builds the form and the insert is with it
//Build log form using query result and exercise name increment ($x)
function buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date, $nameCount, $exerciseIDArray) {
$logSubmit = $_POST['logSubmit'];
if (!isset($logSubmit)) {
echo "<form action='$thisScript' method='POST' name='log' id='log'>\n";
echo "<fieldset>\n";
echo "<legend>$template</legend>\n";
echo "<h2>$exerciseArray[$nameCount]</h2>\n";
echo "<input type='hidden' name='exerciseArray[]' value='$exerciseArray[$nameCount]'/>\n";
$j = 1;
//Generate exercise form with loop
for ($i=0; $i < $setsArray[$i]; $i++) {
echo "<fieldset>";
echo "<legend>Set $j</legend>\n";
//Use $template in a hidden value to work around issue of value being lost after submitting form
echo <<<BODYDOC
<label>Weight</label>
<input type="text" name="weight[]" required /> \n
<label>Reps</label>
<input type="number" name="reps[]" required /> \n
<label>Rest Time</label>
<input type="number" name="rest[]" required /> \n
<label>Notes</label>
<textarea name="notes[]"></textarea>
<input type="hidden" name="set[]" value='$j' />
<input type="hidden" name='mySelect' value='$template' />
</fieldset>
BODYDOC;
$j++;
} //End form for loop
echo "<br /><button type='submit' name='logSubmit'>Submit</button>\n";
echo "</fieldset>\n";
echo "</form>\n";
echo "<p><a href='newday.php'>Back</a></p>\n";
//Increment exerciseNameArray counter so next form dispays next exercise name
} //End if empty submit
if (isset($logSubmit)) {
//POSTed
$template = $_POST['mySelect'];
$set = $_POST['set'];
$weight = $_POST['weight'];
$reps = $_POST['reps'];
$rest = $_POST['rest'];
$notes = $_POST['notes'];
$user = $_SESSION['email'];
//Increment exercise name counter
$nameCount++;
//Update Log
updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date, $nameCount, $exerciseIDArray);
} //End else if
} //End buildLog($template, $x) function
function updateLog($user, $template, $exerciseArray, $set, $weight, $reps, $rest, $notes, $date, $nameCount, $exerciseIDArray) {
//Insert data with query
$numRows = count($exerciseArray);
//Insert user,exercise name, and date
$insert = "INSERT INTO stats_resistance
(user, exerciseName, date)
VALUES
('$user','$exerciseArray[$nameCount]', '$date')"
or
die(mysql_error());
$result = mysql_query($insert)
or
die("<b>Query Failed</b><br>$insert<br>" . mysql_error());
//Query for stat_ID
$query = "SELECT statsID
FROM stats_resistance
WHERE user = '$user'
AND exerciseName = '$exerciseArray[$nameCount]'
AND date = '$date'";
//Get result
$result = mysql_query($query)
or
die("<b>Query Failed</b><br>$query<br>" . mysql_error());
$statsID = mysql_fetch_object($result);
$statsID = $statsID->statsID;
//echo "statsID = " . $statsID;
//Insert into resistanceSets with statsID as foreignKey
//Can insert multiple value sets by including comma after set parentheses
$insert = "INSERT INTO resistanceSets
(statsID, exerciseID, setID, exerciseName, weight, numReps, rest, notes)
VALUES
('$statsID', '$exerciseIDArray[$nameCount]', '$set[0]', '$exerciseArray[$nameCount]', '$weight[0]', '$reps[0]', '$rest[0]', '$notes[0]'),
('$statsID', '$exerciseIDArray[$nameCount]', '$set[1]', '$exerciseArray[$nameCount]', '$weight[1]', '$reps[1]', '$rest[1]', '$notes[1]'),
('$statsID', '$exerciseIDArray[$nameCount]', '$set[2]', '$exerciseArray[$nameCount]', '$weight[2]', '$reps[2]', '$rest[2]', '$notes[2]')";
$result = mysql_query($insert)
or
die("<b>Query Failed</b><br>$insert<br>" . mysql_error());
//buildLog($thisScript, $template, $exerciseArray, $setsArray, $numRows, $date, $nameCount, $exerciseIDArray);
} //End updateLog()
It's a simple matter of ensuring the variable is set, if it is then increment it like any other variable.
if(isset($_SESSION['nameCount'])) {
$_SESSION['nameCount']++;
}
Alternatively, given you've set the value of the session variable to a local variable you can increment this local variable and reassign that value to the session variable. I.e.
$nameCount++;
$_SESSION['nameCount'] = $nameCount;
Both will have the same result.
I am trying to display the customer record from my database thats is determined by the id.
What I already have is a return where the id = 42. What I want to do is make it where the record returned is based on the id number that the user inputs on a previous page, which is $customerid. Any suggestions?
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
You can get the parameter passed to the PHP via GET or POST using $_GET["param_name"] and $_POST["param_name"] respectively.
So if your page is called using
http://path/to/page.php?id=99
You can get 99 in $_GET["id"]
Similar for POST.
Not having seen your form, I am assuming that you will POST the data.
Here is my suggestion for how to handle the data:
$id=isset($_POST['id'])&&is_numeric($_POST['id'])?$_POST['id']:false;
if ($id) {
$result = mysql_query("SELECT id,email FROM people WHERE id = $id;");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
} else {
echo "ERROR: No ID specified.";
}
Also, consider using PDO as mysql_* statements are depreciated. At the least, investigate how to prevent SQL Injection.
Try this:
search.php
<form action="show_record.php" method="post">
<input name="customer_id" />
</form>
show_record.php
<?php
// use $_REQUEST to get a parameter from POST OU GET request method
$id = isset($_REQUEST["customer_id"]) ? $_REQUEST["customer_id"] : 0;
$id = mysql_real_escape_string(); // prevent sql inject
$result = mysql_query("SELECT id,email FROM people WHERE id = '$id'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
So, you can request the page show_record.php from POST or GET, anyway the answer will be the same.
Via GET:
localhost/show_record.php?customer_id=42
My aim is to have a simple, form based CMS so the client can log in and edit the MySQL table data via an html form. The login is working, but the edit page isn't returning the values from the MySQL table, nor am I getting any errors.
I'm still amateur, and I first started the following code for a class project, but now plan to implement it for a live site. From what I understand I shouldn't have to declare the next/previous/etc. variables at the top, which I tried unsuccessfully to do so anyway. Does anything stand out to any of you?:
<?php
echo "<h2>Edit Special Offer</h2><hr>";
if (isset($_COOKIE["username"]))
{
echo "Welcome " . $_COOKIE["username"] . "!<br />";
include "login.php";
}
else
echo "You need to log in to access this page.<br />";
if(isset($previous))
{
$query = "SELECT id, specialtitle, specialinfo
FROM special WHERE id < $id ORDER BY id DESC";
$result = mysql_query($query);
check_mysql();
$row = mysql_fetch_row($result);
check_mysql();
if ($row[0] > 0)
{
$id = $row[0];
$specialtitle = $row[1];
$specialinfo = $row[2];
}
}
elseif (isset($next))
{
$query = "SELECT id, specialtitle, specialinfo
FROM special WHERE id > $id ORDER BY id ASC";
$result = mysql_query($query);
check_mysql();
$row = mysql_fetch_row($result);
check_mysql();
if ($row[0] > 0)
{
$id = $row[0];
$specialtitle = $row[1];
$specialinfo = $row[2];
}
}
elseif (isset($add))
{
$query = "INSERT INTO special (specialtitle, specialinfo)
VALUES ('$specialtitle', '$specialinfo')";
$result = mysql_query($query);
check_mysql();
$id = mysql_insert_id();
$message = "Special Offer Added";
}
elseif (isset($update))
{
$query = "UPDATE special
SET specialtitle='$specialtitle', specialinfo='$specialinfo'
WHERE id = $id";
$result = mysql_query($query);
check_mysql();
$id = mysql_insert_id();
$message = "Monthly Special Updated";
}
elseif (isset($delete))
{
$query = "DELETE FROM special WHERE id = $id";
$result = mysql_query($query);
check_mysql();
$specialtitle = "";
$specialinfo = "";
$message = "Special Offer Deleted";
}
$specialtitle = trim($specialtitle);
$specialinfo = trim($specialinfo);
?>
<form method="post" action="editspecial.php">
<p><b>Special Offer</b>
<br><input type="text" name="specialtitle" <?php echo "VALUE=\"$specialtitle\"" ?>> </p>
<p><b>Special Info/Description</b>
<br><textarea name="specialinfo" rows="8" cols="70" >
<?php echo $specialinfo ?>
</textarea> </p>
<br>
<input type="submit" name="previous" value="previous">
<input type="submit" name="next" value="next">
<br><br>
<input type="submit" name="add" value="Add">
<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
<input type="hidden" name="id" <?php echo "VALUE=\"$id\"" ?>>
</form>
<?php
if (isset($message))
{
echo "<br>$message";
}
?>
Login.php:
<?php
function check_mysql()
{
if(mysql_errno()>0)
{
die ("<br>" . mysql_errno().": ".mysql_error()."<br>");
}
}
$dbh=mysql_connect ("xxxxxxxxxxxxxxxxx","xxxxxxxx","xxxxxxxx");
if (!$dbh)
{
die ("Failed to open the Database");
}
mysql_select_db("xxxxxx");
check_mysql();
if(!isset($id))
{
$id=0;
}
?>
Please please please do a little bit more learning before attempting to build this thing.
You can do it the way you are doing it, but with just a small amount of extra knowledge about OO programming, and maybe about the Pear db classes you will have 3x cleaner code.
If you really choose not to, at the very least, pull each of your save, update, delete, etc procedures out into functions instead of just inlining them in your code. put them in a separate file, and include it in that page.
It may not be useful to you, but I am going to dump a generic table access class here in the page for you. It requires a simple db class API, but if you use this or something like it your life will be 5x easier.
If you don't understand this code when you look at it, that's ok, but please just come back and ask questions about the stuff you don't understand. That is what stackoverflow is for.
This is an older class that should just do basic stuff. Sorry it's not better I just wanted to dig something out of the archives for you that was simple.
<?php
// Subclass this class and implement the abstract functions to give access to your table
class ActiveRecordOrder
{
function ActiveRecordOrder()
{
}
//Abstract function should return the table column names excluding PK
function getDataFields()
{}
//Abstract function should return the primary key column (usually an int)
function getKeyField()
{}
//abstract function just return the table name from the DB table
function getTableName()
{}
/*
This function takes an array of fieldName indexed values, and loads only the
ones specified by the object as valid dataFields.
*/
function loadRecordWithDataFields($dataRecord)
{
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
foreach($dataFields as $fieldName)
{
$this->$fieldName = $dataRecord[$fieldName];
}
}
function getRecordsByKey($keyID, &$dbHandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
$results = $dbHandle->select($tableName, $dataFields, array($keyField => $keyID));
return $results;
}
function search($whereArray, &$dbHandle)
{
$tableName = $this->getTableName();
$dataFields = $this->getDataFields();
$dataFields[] = $this->getKeyField();
return $dbHandle->select($tableName, $dataFields, $whereArray);
}
/**
* Since it is *hard* to serialize classes and make sure a class def shows up
* on the other end. this function can just return the class data.
*/
function getDataFieldsInArray()
{
$dataFields = $this->getDataFields();
foreach($dataFields as $dataField)
{
$returnArray[$dataField] = $this->$dataField;
}
return $returnArray;
}
/**
* Added update support to allow to update the status
*
* #deprecated - use new function saveObject as of 8-10-2006 zak
*/
function updateObject(&$dbHandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataArray = $this->getDataFieldsInArray();
$updatedRows = $dbHandle->updateRow(
$tableName,
$dataArray,
array( $keyField => $this->$keyField )
);
return $updatedRows;
}
/**
* Allows the object to be saved to the database, even if it didn't exist in the DB before.
*
* #param mixed $dbhandle
*/
function saveObject(&$dbhandle)
{
$tableName = $this->getTableName();
$keyField = $this->getKeyField();
$dataArray = $this->getDataFieldsInArray();
$updatedRows = $dbHandle->updateOrInsert(
$tableName,
$dataArray,
array( $keyField => $this->$keyField )
);
return $updatedRows;
}
}
"Welcome " . $_COOKIE["username"] . "!<br />"; [and many other places]
HTML-injection leading to cross-site security holes. You need to use htmlspecialchars every time you output a text value to HTML.
"INSERT INTO special (specialtitle, specialinfo) VALUES ('$specialtitle' [and many other places]
SQL-injection leading to database vandalism. You need to use mysql_real_escape_string every time you output a text value to an SQL string literal.
if (isset($_COOKIE["username"]))
Cookies are not secure, anyone can set a username cookie on the client-side. Don't use it for access control, only as a key to a stored or session user identifier.
You also appear to be using register_globals to access $_REQUEST values as direct variables. This is another extreme no-no.
Between all these security snafus you are a sitting duck for Russian hackers who will take over your site to push viruses and spam.
Be careful with your code there. Your not filtering your cookie value and you shouldn't be storing a username directly in there as it can be easily changed by the visitor. You should look into filter_input for filtering cookie data and eany form data that is being submitted - especially your $_POST['id']
this will save you a lot of heartache further down the line from attacks.
Your if else statements are checking if variables are set but you dont set next, previous, add etc
You are using submit buttons with those values so you would need to check for
if(isset($_POST['previous']))
instead of yours which is
if(isset($previous))
I can't see where you set your database details either unless you have an included file somewhere that you haven't posted. (don't post the real ones of course but i can't see anything)
I don´t know what's happening in login.php, but you're using $id before it is set. That´s just in the first part.
Edit: To clarify, you are using $id in every query statement and setting it afterwards, my guess would be that $id is null and that is why nothing gets returned.
Edit 2: What else is happening in login.php? If you never read your $_POST variables, nothing will ever happen.
Edit 3: Like I already partly said in a comment, your if(isset($previous)) section, elseif (isset($update)) section and elseif (isset($delete)) sections will never do anything as $id is always 0.
After authenticating your user you need to get and filter the posted variables, $_POST['id'], $_POST['previous'], etc.