I was wondering if anyone could help me with this problem i'm having.
I have a ReminderDAO class with methods to delete, edit, insert etc and a Reminder class with a constructor and get and sets.
I then have a a view reminders where it just lists all the reminders out.
I want to be able to add an edit and delete to this view page.
To use the delete and edit functions in my ReminderDAO class, i need to pass a reminder object through the function and i'm not quite sure how to do this.
If anyone could help me that would be of great help, i'm new to this language so i apologise if it's not great code.
Thank you in advance!
Reminder DAO
class ReminderDAO extends DAO {
public function __construct() {
parent::__construct();
}
public function insert($reminder) {
if (!isset($reminder)) {
throw new Exception("Reminder required");
}
$sql = "INSERT INTO Reminders(member_id, title, details, reminder_type) VALUES (?, ?, ?, ?)";
$params = array($reminder->getMember_id(), $reminder->getTitle(), $reminder->getDetails(), $reminder->getType());
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not save Reminder: " . $errorInfo[2]);
}
$sql = "SELECT LAST_INSERT_ID()";
$stmt = $this->link->prepare($sql);
$status = $stmt->execute();
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not retrieve new reminder's id: " . $errorInfo[2]);
}
$row = $stmt->fetch();
$id = $row[0];
$reminder->setId($id);
}
public function delete($reminder) {
if (!isset($reminder)) {
throw new Exception("Reminder required");
}
$id = $reminder->getId();
if ($id == null) {
throw new Exception("Reminder id required");
}
$sql = "DELETE FROM Reminders WHERE id = ?";
$params = array($reminder->getId());
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not delete reminder: " . $errorInfo[2]);
}
}
public function update($reminder) {
if (!isset($reminder)) {
throw new Exception("Reminder required");
}
$id = $reminder->getId();
if ($id == null) {
throw new Exception("Reminder id required");
}
$sql = "UPDATE Reminders SET member_id = ?, title = ?, details = ?, reminder_type = ? WHERE id = ?";
$params = array($reminder->getMember_id(), $reminder->getTitle(), $reminder->getDetails(), $reminder->getType());
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not update Reminder: " . $errorInfo[2]);
}
}
public function getReminder($id) {
$sql = "SELECT * FROM Reminders WHERE id = ?";
$params = array($id);
$stmt = $this->link->prepare($sql);
$status = $stmt->execute($params);
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not retrieve Reminder: " . $errorInfo[2]);
}
$reminder = null;
if ($stmt->rowCount == 1) {
$row = $stmt->fetch();
$id = $row['id'];
$member_id = $row['member_id'];
$title = $row['title'];
$details = $row['details'];
$type = $row['reminder_type'];
$reminder = new ReminderDAO($id, $member_id, $title, $details, $type);
}
return $reminder;
}
public function getReminders() {
$sql = "SELECT * FROM Reminders";
$stmt = $this->link->prepare($sql);
$status = $stmt->execute();
if ($status != true) {
$errorInfo = $stmt->errorInfo();
throw new Exception("Could not retrieve reminders: " . $errorInfo[2]);
}
$reminders = array();
$row = $stmt->fetch();
while ($row != null) {
$id = $row['id'];
$member_id = $row['member_id'];
$title = $row['title'];
$details = $row['details'];
$type = $row['reminder_type'];
$reminder = new Reminder($id, $member_id, $title, $details, $type);
$reminders[$id] = $reminder;
$row = $stmt->fetch();
}
return $reminders;
}
}
?>
Reminder Class
<?php
class Reminder {
private $id;
private $member_id;
private $title;
private $details;
private $reminder_type;
public function __construct($i, $m_id, $title, $det, $type) {
$this->id = $i;
$this->member_id = $m_id;
$this->title = $title;
$this->details = $det;
$this->reminder_type = $type;
}
public function getId() { return $this->id; }
public function getMember_id() { return $this->member_id; }
public function getTitle() { return $this->title; }
public function getDetails() { return $this->details; }
public function getType() { return $this->reminder_type; }
public function setId($i) { $this->id = $i; }
public function setMember_id($mID) { $this->member_id = $mID; }
public function setTitle($t) { $this->title = $t; }
public function setDetails($d) { $this->details = $d; }
public function setType($type) { $this->reminder_type = $type; }
}
?>
View Reminders
<?php
ob_start();
require_once 'includes/Member.php';
require_once 'includes/MemberDAO.php';
require_once 'includes/Reminder.php';
require_once 'includes/ReminderDAO.php';
require_once 'includes/session.php';
confirm_logged_in(); // needs to come before any html because it does a redirect
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
require 'toolbar.php';
$member = ($_SESSION['member']);
$reminderDAO = new ReminderDAO();
$reminders = $reminderDAO->getReminders();
echo "<p>Hello " . $member->getFN() . "</p>";
echo "<p>These are the current reminders: </p>";
foreach ($reminders as $rem) {
echo "<b>Title:</b> " . $rem->getTitle() . "<br />";
echo "<b>Details:</b> " . $rem->getDetails() . "<br />";
echo "<b>Type: </b>" . $rem->getType() . "<br />";
echo "</p>";
}
echo $display; ?>
Add Reminder?
</body>
</html>
<?php ob_flush(); ?>
edit_reminder_form.php class
<?php
ob_start();
require_once 'includes/session.php';
require_once 'includes/Member.php';
require_once 'includes/MemberDAO.php';
require_once 'includes/Reminder.php';
require_once 'includes/ReminderDAO.php';
require_once 'includes/session.php';
confirm_logged_in(); // needs to come before any html because it does a redirect
?>
<?php
$reminderDAO = new ReminderDAO();
$reminder = $reminderDAO->getReminder($_GET['id']);
?>
<html>
<head>
<title>Edit Reminder</title>
</head>
<body>
<table>
<tr>
<td>
<h2>Edit Reminder</h2>
<?php if (isset($_GET['errorMessage'])) echo "<p>".$_GET['errorMessage']."</p>"; ?>
<form action="edit_reminder.php" method="POST">
Title: <input type="text" name="title" value="<?php $reminder->getTitle(); ?>" /><br/>
Details: <input type="text" name="details" value="<?php $reminder->getDetails()?> " /><br/>
<select name="reminder_type" value="<?php $reminder->getType();?>">
<option value="Choose">Please choose a reminder type!</option>
<option value="Bill">Bill</option>
<option value="Shopping">Shopping</option>
<option value="Event">Event</option>
<option value="Birthday">Birthday</option>
<option value="Other">Other</option>
</select>
<br />
<input type="submit" name="reminder" value="Edit Reminder" />
</form>
<br />
Cancel
</td>
</tr>
</table>
</body>
<?php
//5.Close connection
if(isset($connection)) {
mysql_close($connection);
}
?>
</html>
<?php ob_flush(); ?>
You could send the ID of the reminder to the next page where you edit/delete a reminder.
foreach ($reminders as $rem) {
echo "<b>Title:</b> " . $rem->getTitle() . "<br />";
echo "<b>Details:</b> " . $rem->getDetails() . "<br />";
echo "<b>Type: </b>" . $rem->getType() . "<br />";
echo "[<a href='edit.php?id=" . $rem->getID() . "'>Edit</a>] ";
echo "[<a href='delete.php?id=" . $rem->getID() . "'>Delete</a>] ";
echo "</p>";
}
In edit.php you get the reminder object using the ID (e.g. $_GET['id']), load the data from the database using ReminderDAO and create a form populated with the reminder values. In that form, you should also put the reminder id, so when he submit the form to Save changes, you can identify the reminder that was edited.
After saving the changes, you can redirect him back to the list of reminders using header function.
Similar, in delete.php you can delete the reminder using the ID (e.g. $_GET['id']) and then redirect the user to the list of reminders.
Related
I am a PHP OOP newbie and I am currently learning sessions. I have created a session class which is supposed to check if session variable $_SESSION['userID'] is set, and set the login status to true; as well as set the user id.There is also a function, setVars() to set other object properties when called:
session.php
<?php
class Session
{
public $log_in_status=false;
public $userID;
public $fname;
public $class_id;
public $email;
public function __construct()
{
session_start();
if ($_SESSION['userID'])
{
$this->log_in_status = true;
$this->userID = $_SESSION['userID'];
}
else
{
$this->log_in_status = false;
unset($_SESSION['userID']);
}
}
public function setVars($classID, $email, $fname)
{
$this->class_id = $classID;
$this->email = $email;
$this->fname = $fname;
}
}
$session = new Session();
The above class is in a require_once statement in init.php file:
<?php
#init.php
require_once("session.php");
Page1.php sets some properties in the $session instance by calling the setVars method, and after echo them to the screen. However, page2.php is not able to echo these same values from the object properties:
<?php
# page1.php
require_once("init.php");
$class_id = 1;
$email = "test#test.com";
$fname = "Toto The Dog";
$session->setVars($class_id, $email, $fname);
?>
<!DOCTYPE html>
<html>
<head>
<title>Testing sessions</title>
</head>
<body>
<?php
echo "Page 1 <br> <br>";
echo "objectClassID: " .$session->class_id . "<br>";
echo "objectEmail : " . $session->email . "<br>";
echo "objectFname : " . $session->fname . "<br> <br>";
echo "<a href='page2.php'>Go to Page 2</a>";
?>
</body>
</html>
//--------------------------------------------
<?php
# page2.php
require_once("init.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Testing sessions</title>
</head>
<body>
<?php
echo "Page 2 <br> <br>";
echo "objectClassID: " . $session->class_id . "<br>";
echo "objectEmail : " . $session->email . "<br>";
echo "objectFname : " . $session->fname . "<br> <br>";
echo "<a href='page1.php'>Go to Page 1</a>";
?>
</body>
</html>
How can I get page2.php to be able to display the $session object properties?
If you want to persist the vars across pages, you need to store them in the $_SESSION array. For example
<?php
class Session {
public $log_in_status = false;
public $userID;
public $fname;
public $class_id;
public $email;
public function __construct() {
session_start();
if (isset($_SESSION['userID'])) {
$this->log_in_status = true;
$this->userID = $_SESSION['userID'];
}
$this->class_id = isset($_SESSION['class_id']) ? $_SESSION['class_id'] : null;
$this->email = isset($_SESSION['email']) ? $_SESSION['email'] : null;
$this->fname = isset($_SESSION['fname']) ? $_SESSION['fname'] : null;
}
public function setVars($classID, $email, $fname) {
$this->class_id = $_SESSION['class_id'] = $classID;
$this->email = $_SESSION['email'] = $email;
$this->fname = $_SESSION['fname'] = $fname;
}
}
$session = new Session();
I hope you are doing great. I'm having a problem where I cannot insert data into my database. There are multiple reasons to why that happens so don't consider it a duplicate question please. I checked my code. For one table it saves the data but for this table. It displays that the same page was not found and no data is saved on the local database. I hope you can help me guys. Thanks in advance. :)
Here are some useful pieces of code:
<?php
include 'Header.php';
?>
<style>
#first {
//margin-right: 100%;
//clear: both;
}
#first > img {
display: inline-block;
//float: left;
}
#first > p {
//float: left;
display: inline-block;
//margin-left: 60px;
//margin-bottom: 120px;
}
</style>
<!-- Post content here -->
<!-- Then cmments below -->
<h1>Comments</h1>
<!--<?php ?>
if (isset($_GET['id'])) {
$id = $_GET['id'];
} elseif (isset($_POST['id'])) {
$id = $_POST['id'];
} else {
echo '<p class="error"> Error has occured</p>';
include 'footer.html';
exit();
}
$db = new Database();
$dbc = $db->getConnection();
$display = 10; //number of records per page
$pages;
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//use select count() to find the number of users on the DB
$q = "select count(comment_id) from comments";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //calculate the number of pages we will need
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//use LIMIT to specify a range of records to select
// for example LIMIT 11,10 will select the 10 records starting from record 11
$q = "select * from users order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
/*if ($r)
{*/
$result = mysql_query("SELECT * FROM comments WHERE video_id= '" + + "'");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <!--<?php /* echo $row->author; //Or similar in your table ?>
<p>
<?php echo $row->body; ?>
</p>
</div>
<?php
/*} */
?>*/-->
<h1>Leave a comment:</h1>
<form action="Comment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="text" name="comment" value="" />
<input type="hidden" name="submitted" value="TRUE" />
<input type="submit" name="submit" value="Insert"/>
</form>';
<?php
if (isset($_POST['submitted'])) {
$comment = '';
$errors = array();
if (empty($_POST['comment']))
$errors[] = 'You should enter a comment to be saved';
else
$comment = trim($_POST['comment']);
if (empty($errors)) {
include 'Comments_1.php';
$comment_2 = new Comments();
$errors = $comment_2->isValid();
$comment_2->Comment = trim($_POST['comment']);
$comment_2->UserName = hamed871;
$comment_2->Video_Id = 1;
if ($comment_2->save()) {
echo '<div class="div_1"><div id="div_2">' .
'<h1>Thank you</h1><p> your comment has been'
. ' posted successfully</p></div></div>';
}
}
//First check if everything is filled in
/* if(/*some statements *//* )
{
//Do a mysql_real_escape_string() to all fields
//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>
id (auto incremented)
name
email
text
datetime
approved--> */
}
?>
<!--echo '--><div id="first">
<img src="http://www.extremetech.com/wp-content/uploads/2013/11/emp-blast.jpg?type=square" height="42" width="42"/>
<p>hamed1</p>
</div><!--';-->
<dl>
<dt>comment1</dt>
<dd>reply1</dd>
<dd>reply2</dd>
</dl>
<!--//}
/*else
{
}*/
?>-->
<?php
include 'Footer.php';
?>
My Comment class:
<?php
include_once "DBConn.php";
class Comments extends DBConn {
private $tableName = 'Comments';
//attributes to represent table columns
public $comment_Id = 0;
public $Comment;
public $UserName;
public $Video_Id;
public $Date_Time;
public function save() {
if ($this->getDBConnection()) {
//escape any special characters
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
$this->UserName = mysqli_real_escape_string($this->dbc, $this->UserName);
$this->Video_Id = mysqli_real_escape_string($this->dbc, $this->Video_Id);
if ($this->comment_Id == null) {
$q = 'INSERT INTO comments(Comment, User_Id, Video_Id, Date_Time) values' .
"('" . $this->Comment . "','" . $this->User_Id . "','" . $this->Video_Id . "',NOW()')";
} else {
$q = "update Comments set Comment='" . $this->Comment . "', Date_Time='" . NOW() ."'";
}
// $q = "call SaveUser2($this->userId,'$this->firstName','$this->lastName','$this->email','$this->password')";
$r = mysqli_query($this->dbc, $q);
if (!$r) {
$this->displayError($q);
return false;
}
return true;
} else {
echo '<p class="error">Could not connect to database</p>';
return false;
}
return true;
}
//end of function
public function get($video_id) {
if ($this->getDBConnection()) {
$q = "SELECT Comment, Date_Time, UserName FROM Comments WHERE Video='" . $userName."' order by time_stamp";
$r = mysqli_query($this->dbc, $q);
if ($r) {
$row = mysqli_fetch_array($r);
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
return true;
}
else
$this->displayError($q);
}
else
echo '<p class="error">Could not connect to database</p>';
return false;
}
public function isValid() {
//declare array to hold any errors messages
$errors = array();
if (empty($this->Comment))
$errors[] = 'You should enter a comment to be saved';
return $errors;
}
}
?>
Output show when I click insert button:
Not Found
The requested URL /IndividualProject/Comment.php was not found on this server.
Apache/2.4.17 (Win64) PHP/5.6.16 Server at localhost Port 80
I encountered this kind of issue when working on a staging site because webhosting may have different kinds of restrictions and strict. Now what I did is changing the filename for example:
Class name should match the filename coz it's case sensitive.
Comment.php
class Comment extends DBConn {
function __construct () {
parent::__construct ();
}
//code here..
}
I have following code:
<meta charset="UTF-8">
<?php
include_once 'init/init.funcs.php';
function emaili_pikkus(){
global $email;
if (strlen($email)>45){
echo 'e-mail ei tohi olla pikem kui 45 tähemärki';
}
else{
parooli_pikkus();
}
}
function parooli_pikkus()
{
global $parool;
$pikkus = strlen($parool);
if ($pikkus<6){
echo "Parool peab olema vähemalt 6 tähemärki pikk";
}
else {
varasem_olemasolu();
}
}
function varasem_olemasolu()
{
global $email;
if(!empty($_POST['email']))
{
$query = mysql_query("SELECT * FROM kasutajad ") or die(mysql_error());
$array = mysql_fetch_array($query);
if(in_array($email, $array))
{
echo "Selle e-mailiga on kasutaja juba registreeritud.";
}
else
{
paroolide_kattuvus();
}
}
}
function paroolide_kattuvus()
{
$parool = $_POST['parool'];
$parool_uuesti = $_POST['parooluuesti'];
if($parool==$parool_uuesti)
{
NewUser();
}
else{
echo "Paroolid ei kattu.";
{}
}
}
function NewUser()
{
global $sql;
if (mysql_query( $sql))
{
echo "Kasutaja loodud";
}
}
emaili_pikkus();
?>
And file init.funcs.php which contains following:
<?php
session_start ();
$db = mysql_connect ( 'localhost', 'root', 'aaaa' );
$email = mysql_real_escape_string($_POST['email']);
$eesnimi = mysql_real_escape_string($_POST['eesnimi']);
$perekonnanimi = mysql_real_escape_string($_POST['perekonnanimi']);
$parool = $_POST['parool'];
$parool_uuesti = $_POST['parooluuesti'];
$salt = rand(10000,99999);
$hashed_pwd = sha1('$parool'.$salt);
$sql="INSERT INTO kasutajad (e_mail, eesnimi, perenimi, parool, salt ) VALUES ('$email','$eesnimi', '$perekonnanimi', '$parool', '$salt')";
if (! $db) {
header ( "location: /" );
die ();
} else {
mysql_select_db ( 'ta2014' );
}
include_once 'functions/user.funcs.php';
?>
My HTML looks like this:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>Registreerimine</title>
</head>
<body>
<strong>Registreerimiseks täida järgnevad väljad: </strong><br>
<br>
<form method="POST" action="registreerimine4.php">
<table>
<tr><td>Sinu Tieto e-maili aadress: </td><td><input type="text" name="email"></td></tr>
<tr><td>Eesnimi: </td><td><input type="text" name="eesnimi"></td></tr>
<tr><td>Perekonnanimi: </td><td><input type="text" name="perekonnanimi"></td></tr>
<tr><td>Parool: </td><td><input type="text" name="parool"></td></tr>
<tr><td>Parool uuesti: </td><td><input type="text" name="parooluuesti"></td></tr>
</table>
<br>
<input type="submit" value="Registreeri" name="Registreeri">
</form>
</body>
</html>
Now when I run my HTML and PHP everything works properly except one function. varasem_olemasolu() does not work. This function is meant for checking if this email address already has an account registred. Everything worked properly when I used following code, but its too long and overly complicated to really use:
<meta charset="UTF-8">
<?php
function emaili_pikkus(){
$con = mysql_connect("localhost","root","aaaa");
$email = mysql_real_escape_string($_POST['email']);
if (strlen($email)>45){
echo 'e-mail ei tohi olla pikem kui 45 tähemärki';
}
else{
parooli_pikkus();
}
}
function parooli_pikkus()
{
$parool = $_POST['parool'];
$pikkus = strlen($parool);
if ($pikkus<6){
echo "Parool peab olema vähemalt 6 tähemärki pikk";
}
else {
varasem_olemasolu();
}
}
function varasem_olemasolu()
{
$con = mysql_connect("localhost","root","aaaa");
mysql_select_db("ta2014", $con);
$email = mysql_real_escape_string($_POST['email']);
if(!empty($_POST['email']))
{
$query = mysql_query("SELECT * FROM kasutajad ") or die(mysql_error());
$array = mysql_fetch_array($query);
if(in_array($email, $array))
{
echo "Selle e-mailiga on kasutaja juba registreeritud.";
}
else
{
paroolide_kattuvus();
}
}
}
function paroolide_kattuvus()
{
$parool = $_POST['parool'];
$parool_uuesti = $_POST['parooluuesti'];
if($parool==$parool_uuesti)
{
NewUser();
}
else{
echo "Paroolid ei kattu.";
{}
}
}
function NewUser()
{
$con = mysql_connect("localhost","root","aaaa");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ta2014", $con);
$email = mysql_real_escape_string($_POST['email']);
$eesnimi = mysql_real_escape_string($_POST['eesnimi']);
$perekonnanimi = mysql_real_escape_string($_POST['perekonnanimi']);
$parool = $_POST['parool'];
$parool_uuesti = $_POST['parooluuesti'];
$salt = rand(1000000,99999999);
$hashed_pwd = sha1('$parool'.$salt);
$sql="INSERT INTO kasutajad (e_mail, eesnimi, perenimi, parool, salt ) VALUES ('$email','$eesnimi', '$perekonnanimi', '$parool', '$salt')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Kasutaja loodud";
}
emaili_pikkus();
?>
It is a long question and I would be very thankful if someone answers me.
You do not require to fetch complete table record to search email in it. Just change your query as below & check if it returns row is greater than 0.
SELECT * FROM `kasutajad` WHERE `e_mail` = $email
Waring: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Example with PDO:
$email = $_POST['email'];
$con = new PDO( 'mysql:host=localhost;dbname=DB_NAME;charset=UTF-8', 'DB_USER_NAME', 'DB_USER_PASS' );
$query = $con->prepare( "SELECT `e_mail` FROM `kasutajad` WHERE `e_mail` = ?" );
$query->bindValue( 1, $email);
$query->execute();
if( $query->rowCount() > 0 ) { # If rows are found for query
echo "Email Already exits!";
}
else {
echo "Email not found!";
}
I have read the previous questions with similar titles, none seem to provide me with an answer to this particular situation. I am receiving the error mentioned above on a specific functionality. I am not sure what is making it pop up. This is my first development so, unless it is specific to resolving the bug, please leave out the fact that I should be using PDO or mysqli.
this is the function i am trying to instantiate. when the sql command is executed in isolation, it returns the proper results.
public function search_for_candidates_by_technology($technology, $seniority){
$technology = $this->real_escape_string($technology);
$seniority = $this->real_escape_string($seniority);
$this->query("SELECT * FROM candidates WHERE technology LIKE ". $technology ." AND seniority LIKE ". $seniority ."");
}
The class to which the function belongs is tecnoDB
In the actual page where I am trying to instantiate, this is the code:
<form name="buscarBase" action="buscarCV.php" method="POST">Que technologia:<input type="text" name="usertech" value=""/><br/>
Que seniority:<input type="text" name="userSeniority" value="" />
<input type="submit" name="buscar" value="Buscar" />
<input type="submit" name="back" value="Panel de Control"/>
</form>
<table border="black">
<tr><th>Technology</th><th>Seniority</tr>
<?php
$search = tecnoDB::getInstance()->search_for_candidates_by_technology($_POST['usertech'], $_POST['userSeniority']);
while($searchResult = mysql_fetch_array($search)){
echo "<tr><td>" . htmlentities($searchResult['technology']) ."</td>";
echo "<td>". htmlentities($searchResult['seniority']) . "</td></tr>";
}
?>
</table>
The error is coming on the line: while($searchResult = mysql_fetch_array($search))....
That makes me think that the problem is that $search is not being created as an instance. Any ideas?
This is my first project and first question, please be gentle.
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
session_start();
if (!array_key_exists("user", $_SESSION)) {
header('Location: index.php');
exit;
}
require_once("Includes/tecnoDB.php");
$company_id = tecnoDB::getInstance()->get_company_id_by_name($_SESSION['user']);
if ($_SERVER['REQUEST_METHOD'] == "POST"){
if (array_key_exists("back", $_POST)) {
header('Location: companyControlPanel.php' );
exit;
}
else{
$service_user = tecnoDB::getInstance()->verify_service_status($company_id);
$access = $service_user->fetch_row();
if (array_key_exists ("buscar", $_POST)){
if($access[0] < 2 ){
header("Location: selectServicePackage.php" );
exit;
}
}
}
}
// put your code here ?>
<form name="buscarBase" action="buscarCV.php" method="POST">Que tecnologia:<input type="text" name="usertech" value=""/><br/>
Que seniority:<input type="text" name="userSeniority" value="" />
<input type="submit" name="buscar" value="Buscar" />
<input type="submit" name="back" value="Panel de Control"/>
</form>
<table border="black">
<tr><th>Technology</th><th>Seniority</tr>
<?php
$search = tecnoDB::getInstance()->search_for_candidates_by_technology($_POST['usertech'], $_POST['userSeniority']);
while($searchResult = mysql_fetch_array($search)){
echo "<tr><td>" . htmlentities($searchResult['technology']) ."</td>";
echo "<td>". htmlentities($searchResult['seniority']) . "</td></tr>";
}
?>
</table>
</body>
</html>
here goes the tecnoDB class:
class tecnoDB extends mysqli {
// single instance of self shared among all instances
private static $instance = null;
// db connection config vars
private $user = "phpuser";
private $pass = "phpuserpw";
private $dbName = "tecnosearch";
private $dbHost = "localhost";
//This method must be static, and must return an instance of the object if the object
//does not already exist.
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
// The clone and wakeup methods prevents external instantiation of copies of the Singleton class,
// thus eliminating the possibility of duplicate objects.
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public function __wakeup() {
trigger_error('Deserializing is not allowed.', E_USER_ERROR);
}
// private constructor
private function __construct() {
parent::__construct($this->dbHost, $this->user, $this->pass, $this->dbName);
if (mysqli_connect_error()) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
parent::set_charset('utf-8');
}
public function get_company_id_by_name($name) {
$name = $this->real_escape_string($name);
$company = $this->query("SELECT id FROM company WHERE name = '"
. $name . "'");
if ($company->num_rows > 0){
$row = $company->fetch_row();
return $row[0];
} else
return null;
}
public function get_searches_by_company_id($company_id) {
return $this->query("SELECT id, description, technology FROM searches WHERE company_id=" . $company_id);
}
public function create_company ($name, $password){
$name = $this->real_escape_string($name);
$password = $this->real_escape_string($password);
$this->query("INSERT INTO company (name, password) VALUES ('" . $name . "', '" . $password . "')");
}
public function verify_company_credentials ($name, $password){
$name = $this->real_escape_string($name);
$password = $this->real_escape_string($password);
$result = $this->query("SELECT 1 FROM company
WHERE name = '" . $name . "' AND password = '" . $password . "'");
return $result->data_seek(0);
}
public function verify_service_status ($company_id){
$company_id = $this->real_escape_string($company_id);
$service = $this->query("SELECT service FROM company WHERE id = '". $company_id ."'");
return $service;
}
function insert_search($company_id, $description, $technology){
$description = $this->real_escape_string($description);
$technology = $this->real_escape_string($technology);
$this->query("INSERT INTO searches (company_id, description, technology)" .
" VALUES (" . $company_id . ", '" . $description . "','" .$technology. "')");
}
public function search_for_candidates_by_technology($technology, $seniority){
$technology = $this->real_escape_string($technology);
$seniority = $this->real_escape_string($seniority);
$this->query("SELECT * FROM candidates WHERE technology LIKE ". $technology ." AND seniority LIKE ". $seniority ."");
}
}
?>
I fixed the bug by setting the query in search_for_candidates_by_technology = $variable and returning the variable as well as in the actual page requiring the file where I have this function specified. I set the instance of the search_for_candidates_by_technology equal to $variable1 and created another object as the result of $variable1->get_array; . My error messages are now gone but the results are not appearing in the search. I am assuming because the action is on the same page and it causes the page to reload and when it reloads it essentially is resetting. I am looking at using an AJAX to show the results instead but I have never used asynchronous javascript and have only briefly seen XMLs. Any pointers or ideas that won't require AJAX?
I am doing the Lynda.com learning PHP 2 videos and have run into a problem, in that the instructor seems to have neglected to tell us one of the steps he does in the video. I have uploaded the relevant video here http://www.youtube.com/watch?v=fFKgAa7RAjo but will also describe the problem. At 6:40 of the video, after logging in to our application, he arrives at public/admin/index.php which has two links on it. one link allows him to "view log file" which takes him to public/admin/logfile.php and the other link allows him to log out. He doesn't tell us how to make these links. I can obviously make a link to view logfile
View Logfile
but I don't know how to make the link that will log me out, because that will obviously involve some PHP.
I have included below the login.php file, the index.php file (it's redirected to index.php after logging in) and the functions.php file. Do you know how I would logout from this?
This is the login.php file
<?php
require_once("../../includes/initialize.php");
if($session->is_logged_in()){
redirect_to("index.php");
}
//Remember to give your form's submit tag a name="submit" attribute
if (isset($_POST['submit'])) {//Form has been submitted.
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//Check database to see if username/password exist
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
log_action('Login', "{$found_user->username} logged in.");
redirect_to("index.php");
} else {
//username/password combo was not found in the database
$message = "Username/password combination incorrect.";
}
} else {//Form has not been submitted.
$username = "";
$password = "";
}
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Staff Login</h2>
<?php echo output_message($message); ?>
<form action="login.php" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="<?php
echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="<?php
echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="login" />
</td>
</tr>
</table>
</form>
</div>
<?php include_layout_template('admin_footer.php'); ?>
Functions.php
<?php
function strip_zeros_from_date( $marked_string=""){
//first remove the marked zeros
$no_zeros = str_replace('*0', '', $marked_string);
//then remove any remaining marks
$cleaned_string = str_replace('*', '', $no_zeros);
return $cleaned_string;
}
function redirect_to( $location= NULL) {
if($location != NULL) {
header("Location: {$location}");
exit;
}
}
function output_message($message=""){
if (!empty($message)) {
return "<p class=\"message\">{$message}</p>";
} else {
return "";
}
}
function __autoload($class_name) {
$class_name = strtolower($class_name);
$path = LIB_PATH.DS."{$class_name}.php";
if(file_exists($path)){
require_once($path);
} else {
die("The file {$class_name}.php could not be found.");
}
}
function include_layout_template($template=""){
include(SITE_ROOT.DS.'public'.DS.'layouts'.DS.$template);
}
function log_action($action, $message=""){
$logfile = SITE_ROOT.DS.'logs'.DS.'log.txt';
$new = file_exists($logfile) ? false : true;
if($handle = fopen($logfile, 'a')) { //apppend
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
$content = "{$timestamp} | {$action}: {$message}\n";
fwrite($handle,$content);
fclose($handle);
if($new) {chmod($logfile, 0755); }
} else {
echo "Could not open log file for writing.";
}
}
?>
Index.php
<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Menu</h2>
</div>
<?php include_layout_template('admin_footer.php'); ?>
Update
Initialize.php
<?php
//Directory_separator is a PHP pre-defined constant
// (\ for windows, / for Unix)
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('SITE_ROOT') ? null :
define('SITE_ROOT', DS.'hsphere'.DS.'local'.DS.'home'.DS.'c263430'.DS.'quoralist.com');
// define('SITE_ROOT', realpath(dirname(__FILE__).'/../'));
//echo SITE_ROOT."<br/>";
defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes');
// die(LIB_PATH);
//echo LIB_PATH."<br/>";
require_once(LIB_PATH.DS."config.php");
require_once(LIB_PATH.DS."functions.php");
require_once(LIB_PATH.DS."session.php");
require_once(LIB_PATH.DS."database.php");
require_once(LIB_PATH.DS."database_object.php");
require_once(LIB_PATH.DS."user.php");
//echo("You die here");
?>
User.php
<?php
require_once(LIB_PATH.DS.'database.php');
class User extends DatabaseObject{
protected static $table_name="users";
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public function full_name() {
if(isset($this->first_name) && isset($this->last_name)) {
return $this->first_name . " " . $this->last_name;
} else {
return "";
}
}
public static function authenticate($username="",$password="") {
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$sql = "SELECT * FROM users ";
$sql .= "WHERE username = '{$username}' ";
$sql .= "AND password = '{$password}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
//common database methods
public static function find_all(){
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql=""){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record){
$object = new self;
//$object->id = $record['id'];
//$object->username = $record['username'];
//$object->password = $record['password'];
//$object->first_name = $record['first_name'];
//$object->last_name = $record['last_name'];
foreach($record as $attribute=>$value) {
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
?>
Session.php
<?php
class Session {
private $logged_in=false;
public $user_id;
function __construct() {
session_start();
$this->check_login();
if($this->logged_in){
//actions to take right away if user is logged in
} else {
//actions to take right away if user is not logged in
}
}
public function is_logged_in() {
return $this->logged_in;
}
public function login($user) {
//database should find user based on username/password
if($user){
$this->user_id = $_SESSION['user_id'] = $user->id;
$this->logged_in = true;
}
}
public function logout(){
unset($_SESSION['user_id']);
unset($this->user_id);
$this->logged_in = false;
}
private function check_login(){
if(isset($_SESSION['user_id'])){
$this->user_id = $_SESSION['user_id'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
?>
<?php
session_start();
session_destroy();
?>
That should destroy all variables stored in the session. It is really primitive logging out, but it should work. After you do that just redirect to "index.php" or whatever page you want.