I am creating a website with MVC architecture and without framework. There are comments like in a blog. I would like to be possible to answer to a comment. But the answer functionnality does not work (when I wanna answer a comment, it is the same as a first comment) and I have difficulties finding why? Could you help me? Here is the adress of the website : cedricjager.com/stream
Here is connection.php:
class Connection {
// Connection
private function getBdd() {
try {
$bdd = ConfigDB::database();
$pdo = new PDO("mysql:host={$bdd['host']}; dbname={$bdd['db_name']}", "{$bdd['username']}", "{$bdd['password']}");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
return $pdo;
}
// Query
public function query($sql, $params = array(), $fetch = null) {
try {
$req = self::getBdd()->prepare($sql);
$req->execute($params);
if ($fetch == 'one') {
return $req->fetch();
} else if ($fetch == 'all') {
return $req->fetchAll();
} else {
return $req;
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
Here is the model :
<?php
require_once 'Connection.php';
class Critics extends Connection{
//Récupère les critiques selon l'id de l'article.
public function findAllById($post_id) {
$sql = "SELECT *, DATE_FORMAT(date, '%d/%m/%Y à %H:%i') AS date
FROM critics
WHERE id_movie = ?";
$params = [$post_id];
$comms = $this->query($sql,$params,'all');
$critics_by_id = [];
foreach ($comms as $comm) {
$critics_by_id[$comm['id']] = $comm;
}
return $critics_by_id;
}
//Récupèrer les critiques qui ont des enfants.
public function findAllWithChildren($post_id, $unset_children = true) {
$comms = $critics_by_id = $this->findAllById($post_id);
foreach ($comms as $id => $comm) {
if ($comm['parent_id'] != 0) {
$critics_by_id[$comm->parent_id]->children[] = $comm;
if ($unset_children) {
unset($comms[$id]);
}
}
}
return $comms;
}
//récupèrer une critique signalée.
public function findCritics() {
$sql = "SELECT *,DATE_FORMAT(date, '%d/%m/%Y à %H:%i') AS date FROM critics WHERE report=1";
$req = $this->query($sql);
return $req;
}
public function noCritic() {
if ($this->findCritics() == false) {
$msg = '<div class="alert alert-warning">Il n\'y a pas de critiques signalées.</div>';
return $msg;
}
}
//insérer une critique.
public function insertCritic(){
if(isset($_POST['content']) && !empty($_POST['content'])){
$parent_id = isset($_POST['parent_id']) ? $_POST['parent_id'] : 0;
$depth = 0;
if ($parent_id != 0){
$sql = 'SELECT id, depth FROM critics WHERE id = ?';
$params = [$parent_id];
$comm = $this->query($sql,$params, 'one');
if ($comm == false) {
throw new Exception("Ce parent n'existe pas");
}
$depth = $comm->depth + 1;
}
if ($depth >= 3) {
echo "Impossible de rajouter une critique";
}
else {
$sql = 'INSERT INTO critics SET content = ?, author = ?, id_movie = ?, parent_id = ?, date = NOW(), depth = ?';
$params = array($_POST['content'], $_POST['nom'], $_GET['id'], $parent_id, $depth);
$req = $this->query($sql,$params);
}
}
}
}
}
Controller :
public function single() {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$msg = $this->comment->reportCritic();
$this->comment->insertCritic();
$critics = $this->comment->findAllWithChildren($_GET['id']);
$view = require 'Views/single.php';
} else {
header('Location:index.php?p=404');
}
}
Views
<div class="sectioncomments" id="comments">
<?php foreach($critics as $critic): ?>
<?php require('comments.php'); ?>
<?php endforeach; ?>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div id="form-comment" class=" panel panel-default formComment">
<div class="panel panel-heading">
<h4>Poster une critique</h4>
<br>
<span class="return"></span>
</div>
<div class="panel panel-body">
<form method="post" class="form-group form-horizontal">
<div class="form-group">
<div class="col-sm-9">
<input type="text" class="form-control" id="nom" placeholder="Votre nom..." name="nom">
</div>
</div>
<div class="form-group">
<div class="col-sm-9">
<textarea class="form-control" id="content" placeholder="Votre critique..." name="content"></textarea>
</div>
</div>
<p class="text-right"><button type="submit" class="btn btn-success">Publier</button></p>
<input type="hidden" name="parent_id" id="parent_id" value="0" >
</form>
</div>
</div>
</div>
</div>
</div>
Comments.php
<div id="comment-<?= $critic['id'] ?>">
<p>
<b><?= $critic['author'] ?></b>
<span class="text-muted">le <?= $critic['date'] ?></span>
</p>
<div class="blockquote">
<blockquote>
<?= htmlentities($critic['content']) ?>
</blockquote>
</div>
<div class="formulaire">
<form class="form-group" method="post">
<p class="text-left">
<input type="hidden" name="valeur" value="<?= $critic['id_movie'] ?>">
<input type="hidden" name="idval" value="<?= $critic['id'] ?>">
<?php if($critic['depth'] <= 1): ?>
<button type="button" class="reply btn btn-default" data-id="<?= $critic['id'] ?>"><i class="fas fa-comments"></i></button>
<?php endif; ?>
<button type="submit" name="signal" class="btn btn-default"><i class="fas fa-bolt"></i></span></button>
</p>
</form>
</div>
</div>
<div id="answer">
<?php if(isset($critic['children'])): ?>
<?php foreach($critic['children'] as $critic): ?>
<?php require('comments.php'); ?>
<?php endforeach; ?>
<?php endif; ?>
</div>
First, I believe that you never set the children index mentionned in your 'comment.php' view :
<?php if(isset($critic['children'])): ?>
<?php foreach($critic['children'] as $critic): ?>
<?php require('comments.php'); ?>
<?php endforeach; ?>
<?php endif; ?>
Then you should not call two time in a row findAllById for perfomances purpose.
If I where you, maybe I fetch all One time and then build a tree based on what data you get from your query. It allow you to get an infinite nested comments capabilities.
You can do it this way :
$critics = $this->getAllById($id);//movie id
$childs = []; //Will contain all childs indexed by parent_id
$index = []; //will contain all root critics (no parent)
foreach($critics as &$v){
if($v['parent_id'] === 0){ //if no parent, then add to $index
$indexes[$v['id']] = $v;
} else{ //else create an array in $childs at index parent_id
if(!isset($childs[$v['parent_id']])) $childs[$v['parent_id']] = [];
$childs[$v['parent_id']][] = $v;
}
}
//Then you can build your result :
foreach($childs as $id=>&$child){
$parent= $index[$id] ?? $child[$id] ?? null; // search for the parent of the current child
if(is_null($parent)) continue; // a parent doesn't exists anymore, we ignor it, but you can throw an exception instead
if(!isset($parent['children'])) $parent['children'] = [];
$parent['children'][] = $child;
}
return $index;
Now critic should have a 'children' index where are listed all childs. It allow you to build a tree of comments without limit.
All you have to keep in mind, is to correctly set the parent_id when post a new comment.
Let me know if it solves your problem.
Related
I'm currently doing a private chat (style messenger), and I got a problem..
I have a href a link which sends an ID using GET to another page, the thing is that on the other page I load a jquery script which again sends to another page, suddenly it no longer finds the ID GET, what should I do? I want to actualise the page (the messages) thanks (noted that I'm new, I'm not enough good to use ajax or something..)
message.php
message
<?php
// $allUsers = 'SELECT * FROM members WHERE name LIKE "%cc%" ORDER BY id DESC' / SEARCH MEMBERS
$allUsers = $dbh->query('SELECT * FROM members ORDER BY id DESC LIMIT 0, 5');
if ($allUsers->rowCount() > 0)
{
while ($user = $allUsers->fetch())
{
?>
<div id="s_un_main">
<div class="s_un_main_pun">
<img src="../images/avatar/<?php echo $user['avatar'];?>">
<p><?php echo $user['name']; ?></p>
</div>
<div class="s_un_main_pdeux">
<a class="private" target="_blank" href="private.php?id=<?php echo $user['id']; ?>">Message</a>
</div>
</div>
<?php
}
}
else
{
echo "<p>" . "Aucun utilisateur trouvé. " . "</p>";
}
?>
private.php
private
<div id="get_name">
<?php
// USERINFO
if (isset($_SESSION['id']) AND !empty($_SESSION['id']))
{
$getid = $_GET['id'];
$req = $dbh->prepare('SELECT * FROM members WHERE id = :getid');
$req->bindValue('getid', $getid);
$req->execute();
$userinfo = $req->fetch();
}
?>
<div>
<img id="img_header" width="50" src="../images/avatar/<?php echo $userinfo['avatar'];?>">
</div>
<?php echo "<p>" . $userinfo['name'] . "</p>"; ?>
</div>
<section id="zz">
<div id="show_msg">
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
</div>
</section>
<form id="private_form" method="POST" action="">
<textarea name="message"></textarea>
<input type="submit" name="send"></input>
</form>
<script>
setInterval('load_messages()', 1500);
function load_messages()
{
$('#zz').load('private_message.php');
}
</script>
private_message.php
error
<!-- DB -->
<?php include("../db/db.php"); ?>
<!-- DB -->
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
var_dump($getid);
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
var_dump($id) = not found
I'm redoing the whole post since I had hard time explaining the issue or question.
What this code does:
The user can create a new training session. They can name it and if they want to, they can copy the content from previously created session.
I'm using Bootstrap 4 list group items to show the previous sessions. My problem is that I can not catch the user selection to post the data to activateSaveTrainingSession.php, which includes the SQL query to insert the new data to the database.
I can pass the data from the form to the action php file from inputSessionName -input. As you can see, I've also tried using input type="hidden". It kind of works, but it only uses the $sessionId from the first row it fetches, not the user selection. And thats the problem: how do I catch which list item the user selects, so I can post the data to the activateSaveTrainingSession.php?
<div class="row">
<div class="col-lg-12">
<form class="was-validated" action="activateSaveTrainingSession.php" method="post">
<div class="custom-control">
<div class="form-group">
<label for="inputSessionName" class="float-left"><?php echo $lang['TRAINING_SESSIONNAME_HEADER'] ?></label>
<input type="text" class="form-control" id="inputSessionName" name="inputSessionName" placeholder="Example 1" minlength="3" maxLength="128" required>
<small id="inputSessionNameHelp" class="form-text text-muted">
<?php echo $lang['TRAINING_SESSIONNAME_HELPTEXT'] ?>
</small>
</div>
</div>
<h5 class = "mt-3"><?php echo $lang['TRAINING_COPYSESSION_HEADER'] ?></h5>
<div class="row mt-3">
<div class="col-lg-6 mb-3">
<div class="list-group" id="list-tab" role="tablist">
<a class="list-group-item list-group-item-action active" id="list-doNotCopy-list" data-toggle="list" href="#list-doNotCopy" role="tab" aria-controls="list-doNotCopy">Do not copy</a>
<?php
$stmt = $link->prepare('SELECT `id`, `sessionName`, `createDate` FROM `trainingSessions` WHERE `userId` = ? ORDER BY `id` DESC LIMIT 5');
$stmt->bind_param('i', $currentUserId);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($sessionId, $sessionName, $sessionNameDate);
$sessionCounter = 0;
$tabsArray = array();
if ($stmt->num_rows > 0) {
while ($stmt->fetch()) {
$sessionNameDateFixed = date("d.m.Y", strtotime($sessionNameDate));
$sessionCounter += 1;
$listId = "list-$sessionId-list";
$tabId = "list-$sessionId";
array_push($tabsArray, $sessionId)
?>
<a class="list-group-item list-group-item-action" id="<?php echo $sessionId ?>" data-toggle="list" href="#<?php echo $tabId ?>" role="tab" aria-controls="<?php echo $tabId ?>"><?php echo $sessionName ?><input type='hidden' name='copySession' value='<?php echo $sessionId ?> '/></a>
<?php
}
} else {
echo "No results.";
}
$stmt->close();
echo "Displaying last $sessionCounter records.";
?>
</div>
</div>
<div class="col-lg-6">
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade" id="list-doNotCopy" role="tabpanel" aria-labelledby="list-doNotCopy-list">Do not copy data from previous session.</div>
<?php
foreach ($tabsArray as $session) {
$tabsTextArray = array();
$stmt = $link->prepare('SELECT trainingSessions.id, workouts.workoutName, exercises.setNumber, exercises.reps, exercises.weights FROM workouts INNER JOIN exercises ON workouts.id = exercises.workoutId INNER JOIN trainingSessions on trainingSessions.id = exercises.sessionId WHERE exercises.userId = ? AND trainingSessions.id = ? ORDER BY exercises.id DESC');
$stmt->bind_param('ii', $currentUserId, $session);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($sessionId, $workoutName, $set, $reps, $weights);
if ($stmt->num_rows > 0) {
while ($stmt->fetch()) {
$tabText = "<strong>$workoutName</strong> sarja $set, $reps x $weights kg<br>";
array_push($tabsTextArray, $tabText);
}
}
$listId = "list-$sessionId-list";
$tabId = "list-$sessionId";
?>
<div class = "tab-pane fade" id="<?php echo $tabId ?>" role = "tabpanel" aria-labelledby = "<?php echo $listId ?>"><?php
foreach ($tabsTextArray as $text) {
echo "$text";
}
?>
</div>
<?php
}
$stmt->close();
?>
</div>
</div>
</div>
<button type="submit" name="buttonSaveTrainingSession" class="btn btn-success float-left">
<i class="fas fa-sd-card"></i>
<?php echo $lang['TRAINING_BTN_SAVE'] ?>
</button>
</form>
</div>
</div>
activateSaveTrainingSession.php
<?php
require_once('config/sql.php');
include_once('config/common.php');
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
$currentUserId = $_SESSION["currentUserId"];
$submitButton = strip_tags(trim($_POST['buttonSaveTrainingSession']));
if (isset($submitButton)) {
$inputSessioName = filter_var(trim($_POST["inputSessionName"]), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$copySessionID = filter_var(trim($_POST["copySession"]), FILTER_SANITIZE_NUMBER_INT);
if (empty($inputSessioName) && strlen($inputSessioName) < 3 && $inputSessioName > 128) {
header("location: training.php?msg=invalidSessionName");
} else {
echo "Name: $inputSessioName <br>";
echo "ID: $copySessionID";
}
} else {
header("location: 404.php");
}
?>
I think I understand your problem.
You send in the form several fields:
<input type = 'hidden' name = 'copySession' ...>
which have the same name and not in table form! so it is normal that when receiving the request:
$_POST["copySession"]
you get only one and therefore the first.
If you want to send them all, you have to do:
<input type = 'hidden' name = 'copySession[]' ...>
and you get the request as an array.
foreach($_POST["copySession"] as $sessionId){ ... }
If you want to send only one field, you must make them disabled with javascript in real time during the selection.
For example you put in all fields copySession disabled and you add a class to them. Then you add the same class on the button as well and when the user clicks on a button, the field concerned removes the disabled.
With jQuery something like:
//Click on button
$('a.specialClass').on('click', function(){
//Disabled all copySession inputs
$('input[name="copySession"]').prop('disabled', true);
//Let the field concerned able to be send
$('input.specialClass[name="copySession"]').prop('disabled', false);
});
Good luck!
Building a school management system using only PHP and PDO - college project.
Now I'm using MVC, and I'm having trouble sending information from one view to another.
This is the View I want information from
<?php
include_once 'model/student.php';
include_once 'model/courses.php';
$selected = new Student();
$students = Student::getAllStudents();
$selected2 = new Course();
$courses = Course::getAllCourses();
?>
<div>
<div class="col-lg-6">
<span style="font-size: 24px;"> <u>Students</u> - <button style="color:black;width: 30px;height: 35px;">+</button></span>
<br>
<hr>
<?php /* this is where I have the problem, the href attribute - I'm not sure I am sending the information correctly */
foreach($students as $stu){
?> <div> Student Name: <a href='? controller=student&action=showstudent&student_id=<?php echo $stu->id ?>'> <?php echo $stu->name ?> </a></div><br>
<div> Student Phone: <?php echo $stu->phone ?> </div><br> <hr> <?php
}
?>
</div>
<div class="col-lg-6">
<span style="font-size: 24px;"> <u>Courses</u> - <button style="color:black;width: 30px;height: 35px;">+</button></span>
<br>
<hr>
<?php
foreach($courses as $cur){
echo "<span><a href='#' ><b><u><i>" .$cur->name . "</i></u></b></a></span></br><hr>";
}
?>
</div>
</div>
These are the Controller and Model
<?php
class StudentController {
public $student_model;
public function __construct() {
$this->student_model= new Student();
}
public function showstudent($id) {
$find = $this->student_model->findStudentById($id);
if($find==TRUE){
require_once 'views/pages/container/student_into_container.php';
}
else{
echo "error";
}
}
}
Model
<?php
require_once 'connection.php';
class Student{
public $name;
public $phone;
public $email;
public $img;
public $id;
public function __construct() {
}
public static function getAllStudents(){
$students = [];
$db = Db::getInstance();
$req = $db->query('SELECT id, name, phone, email, image FROM students');
$students_info = $req->fetchAll();
foreach ($students_info as $student_info){
$stu = new Student;
$stu->id = $student_info['id'];
$stu->name = $student_info['name'];
$stu->phone = $student_info['phone'];
$stu->email = $student_info['email'];
$stu->img = $student_info['image'];
array_push($students, $stu);
}
return $students;
}
public function findStudentById($id){
$db = Db::getInstance();
$req = $db->prepare('SELECT * FROM student WHERE id = :id');
$req->execute(array('id' => $id));
$student = $req->fetch();
return $student;
}
}
And this is the view I want to get the $id from a student I found
and show all his value fields - this is the student_into_container.php from the StudentController page
<?php
require_once 'connection.php'
?>
<div style="" class="">
<div class="col-lg-4 ">
<?php
require_once 'views/pages/container/student_courses_aside.php';
?>
</div>
<div style="color: black;" class="col-lg-8 blackboard ">
<div class="blackboard-container" style="margin-top:10px;font-size:36px;">
<?php foreach($students as $stu){
echo "<span> Student Name: <a href='#'>". $stu->name . "</a></span></br>";
echo "<span> Student Phone: " . $stu->phone . "</span></br> <hr>";
}
?>
</div>
</div>
</div>
Totally lost here, any help would help.
In short?
Show in once view an information sent from another view with an href attribute
hi i need help i have problem in my code and i can't figure the solutions please help me .
this is the dashboard:
image dashboard
and this is problem after click on delete:
delete problem
and this is my code php of posts file:
<?php
/*
===========================================================
=== Manage Members Page ===
=== You can add | edit | delete Members from here ===
===========================================================
*/
session_start();
if (isset($_SESSION['Username'])) {
include 'init.php';
$pageTitle = 'Posts';
$do = isset($_GET['do']) ? $_GET['do'] : 'Manage' ;
//Start Manage Page
if ($do == 'Manage'){ // Manage Members Page
$sort = 'ASC';
$sort_arry = array('ASC', 'DESC');
if(isset($_GET['sort']) && in_array($_GET['sort'], $sort_arry)) {
$sort = $_GET['sort'];
}
$stmt2 = $con->prepare("SELECT * FROM posts ORDER BY Ordering $sort");
$stmt2->execute();
$rows = $stmt2->fetchAll();
?>
<h1 class="text-center"> Manage Posts </h1>
<div class="container categories">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-edit"></i> Manage Posts
<div class="ordering pull-right">
<i class="fa fa-sort"> </i>Ordering: [
<a class="<?php if ($sort == 'ASC') { echo 'active'; } ?>" href="?sort=ASC">Asc </a> |
<a class="<?php if ($sort == 'DESC') { echo 'active'; } ?>" href="?sort=DESC">Desc </a>
]
</div>
</div>
<div class="row">
<?php
foreach ($rows as $image) {
echo '<div class="col-md-3 col-sm-4 "><div class="thumbnail">';
echo '<h2 class="h4">'.$image['Name']. '</h2><div class="main">';
echo '<img src="data:image;base64,'.$image['Image'].' " alt="image name" title="image title" width="255" heigth="255">';
echo '</div>';
echo '<table class="table table-bordered">';
echo '<tr>';
echo '<td>' . "<a href='posts.php?do=Edit&id=". $image['ID'] ."' class='btn btn-xs btn-primary'><i class='fa fa-edit'></i> edit</a>" . '</td>';
echo '<td>' . "<a href='posts.php?do=Delete&id=". $image['ID'] ."' class='btn btn-xs btn-danger'><i class='fa fa-close'></i> Delete</a>" . '</td>';
echo '</tr>';
echo '</table>';
echo '</div>';
echo '</div>';
}
?>
</div>
<?php } elseif ($do == 'Add') { //add Member page ?>
<h1 class="text-center"> ajouter un nouveau post </h1>
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data" action="?do=Insert" method="POST">
<!-- start Username fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-sm-10 col-md-8">
<input type="text" name="image-name" class="form-control" autocomplete="off" placeholder="username pour se connecter dans le site Web" required />
</div>
</div>
<!-- end Username fieled -->
<!-- start Password fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Image</label>
<div class="col-sm-10 col-md-8">
<input type="file" name="image" class="form-control" placeholder="mot de passe doit être difficile et complexe" required/>
</div>
</div>
<!-- end Password fieled -->
<!-- start Full name fieled -->
<div class="form-group">
<label class="col-sm-2" for="categorie">Categories:</label>
<div class="col-sm-10 col-md-8">
<select class="form-control" name="categorie">
<?php
$stmt = $con->prepare("SELECT * FROM `categories`");
// Execute the Statments
$stmt->execute();
// Assign to variable
$rows = $stmt->fetchAll();
?>
<?php
foreach ($rows as $cat) {
echo "<option value='" . $cat['ID'] . "'>". $cat['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<!-- end Full name fieled -->
<!-- start submit fieled -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="Ajouter" class="btn btn-primary" />
</div>
</div>
<!-- end submit fieled -->
</form>
</div>
<?php
} elseif ($do == 'Insert') {
//insert Members Page
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<h1 class='text-center'> insert an post </h1>";
echo "<div class='container'>";
// Get variable from the form
$name = $_POST['image-name'];
$image= addslashes($_FILES['image']['tmp_name']);
$image= file_get_contents($image);
$image= base64_encode($image);
$cat = $_POST['categorie'];
//validate the form
$formErrors = array();
if (strlen($name) < 4) {
$formErrors[] = "title name cant be less then <strong> 4 caracter</strong>";
}
if (strlen($name) > 20) {
$formErrors[] = "title name cant be More then <strong> 20 caracter</strong>";
}
if (empty($name)) {
$formErrors[] = "Username Cant Be <strong>Empty</strong>";
}
// loop into eroos array and echo it
foreach ($formErrors as $Error) {
echo "<div class='alert alert-danger'>" . $Error . "</div>";
}
// check if There is no error procced the operations
if (empty($formErrors)) {
// check if user exist in database
$check = checkItem("Username", "users", $user);
if ($check == 1) {
$theMsg = "<div class='alert alert-danger'> Sorry this user is exist </div>";
redirectHome($theMsg, 'back');
} else {
// Insert User info into database
$stmt = $con->prepare("INSERT INTO posts(Name, Image, Cat_id)
VALUES (:name, :image, :cat)");
$stmt->execute(array(
'name' => $name,
'image' => $image,
'cat' => $cat,
));
// echo success message
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Inserted </div> ';
redirectHome($theMsg, 'back', 5);
}
}
} else {
echo "<div class='container'>";
$theMsg = '<div class="alert alert-danger"> Sorry you cant browse this page directely </div>';
redirectHome($theMsg, 'back', 5); // 6 is secend of redirect to page in function
echo "</div>";
}
echo "</div>";
} elseif ($do == 'Edit') { // Edit Page
//check if GET request userid Is numeric & Get The integer value of it
$post = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
//sellect All Data Depend On This ID
$stmt = $con->prepare("SELECT * FROM posts WHERE ID = ? LIMIT 1");
// execute Query
$stmt->execute(array($post));
//fetch the Data
$row = $stmt->fetch();
// The row count
$count = $stmt->rowCount();
// If Ther's Such Id show The Form
if ($count > 0) { ?>
<h1 class="text-center"> Modifier Post </h1>
<div class="container">
<form class="form-horizontal" enctype="multipart/form-data" action="?do=Update" method="POST">
<div class="col-md-6 col-md-offset-3 panel">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>
<!-- start title fieled -->
<div class="form-group">
<label class="col-sm-2 control-label">Titre</label>
<div class="col-sm-10 col-md-8">
<input type="text" name="name" class="form-control" autocomplete="off" required value="<?php echo $row['Name']; ?>" >
</div>
</div>
<!-- end title field -->
<!-- start image filed -->
<div class="form-group">
<label class="col-sm-2 control-label">image</label>
<div class="col-sm-10 col-md-8">
<input type="file" name="image" class="form-control" />
</div>
</div>
<!-- end image filed -->
<!-- start Categories filed -->
<div class="form-group">
<label class="col-sm-2" for="categorie">Categories:</label>
<div class="col-sm-10 col-md-8">
<select class="form-control" name="categorie">
<?php
$stmt = $con->prepare("SELECT * FROM `categories`");
// Execute the Statments
$stmt->execute();
// Assign to variable
$rows = $stmt->fetchAll();
?>
<?php
foreach ($rows as $cat) {
echo "<option value='" . $cat['ID'] . "'>". $cat['Name'] . "</option>";
}
?>
</select>
</div>
</div>
<!-- Categories end-->
<!-- start submit fieled -->
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="sauvegarder" class="btn btn-primary" />
</div>
</div>
<!-- end submit fieled -->
</div>
</form>
</div>
<?php
// if there's No Such id Show Error Message
} else {
echo "<div class='container'>";
$theMsg = "<div class='alert alert-danger'>Theres is no such Id</div>";
redirectHome($theMsg);
echo "</div>";
}
} elseif ($do == 'Update') {
echo "<h1 class='text-center'> mis a jour Membre </h1>";
echo "<div class='container'>";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get variable from the form
$id = $_POST['id'];
$name = $_POST['name'];
$image = addslashes($_FILES['image']['tmp_name']);
$image = file_get_contents($image);
$image = base64_encode($image);
$cat = $_POST['categorie'];
//validate the form
$formErrors = array();
if (empty($name)) {
$formErrors[] = "<div class='alert alert-danger'>Username Cant Be <strong>Empty</strong> </div>";
}
if (empty($image)) {
$formErrors[] = "<div class='alert alert-danger'>FullName Cant Be <strong>Empty</strong></div>";
}
if (empty($cat)) {
$formErrors[] = "<div class='alert alert-danger'>Email Cant Be <strong>Empty</strong></div>";
}
// loop into eroos array and echo it
foreach ($formErrors as $Error) {
echo $Error;
}
// check if There is no error procced the operations
if (empty($formErrors)) {
// Update The Database With This Info
$stmt = $con->prepare("UPDATE posts SET Name = ? , Image = ? , Cat_id = ? WHERE ID = ?");
$stmt->execute(array($name, $image, $cat, $id));
// echo success message
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Updated </div> ';
redirectHome($theMsg, 'back');
}
} else {
$theMsg = '<div class="alert alert-danger">Sorry you cant browse this page directely </div>';
redirectHome($theMsg);
}
echo "</div>";
}
elseif ($do == 'Delete') { // Delete Member Page
echo "<h1 class='text-center'> Delete Membre </h1>";
echo "<div class='container'>";
//check if GET request userid Is numeric & Get The integer value of it
$id = isset($_GET['id']) && is_numeric($_GET['id']) ? intval($_GET['id']) : 0;
//sellect All Data Depend On This ID
$check = checkItem('id', 'posts', $id);
// If Ther's Such Id show The Form
if ($check > 0) {
$stmt = $con->prepare("DELETE FROM users WHERE ID = :id");
$stmt->bindParam(":id", $id);
$stmt->execute();
$theMsg = "<div class='alert alert-success'>" . $stmt->rowCount() . ' Record Deleted </div> ';
redirectHome($theMsg);
} else {
$theMsg = "<div class='alert alert-danger'>This id not exist</div>";
redirectHome($theMsg);
}
echo "</div>";
}
include $tpl . 'footer.php';
} else {
header('Location: index.php') ;
exit();
}
from the error, id is the problem.
isset($_GET['id']) && is_numeric($_GET['id'])
i think what u want is
(isset($_GET['id']) && is_numeric($_GET['id']) )//close parantheses in wrong position
i've been debbuging it many times based on my knowledge, i am new to codeigniter, any solution idea would be much appreciated... ty
here's my code
MODEL:
function userdisplay_info($id){
$result = $this->db->query("SELECT uid FROM user WHERE userIdentificationNumber LIKE '$id'");
//if($result->num_rows() > 0){
$info_data = $result->result();
$row = $info_data[0];
$result->free_result();
}
CONTROLLER:
function r_book(){
$data = array();
$bid = $this->input->post('bid');
$u_id = $this->input->post('userinputid');
$data = array(
'book_reserved' => 1
);
if($this->module2->reserved_book($bid,$data))
{
$data['info'] = $this->module2->userdisplay_info($u_id);
$this->load->view('User/template/header');
$this->load->view('User/template/navigator');
$this->load->view('User/landingpage',$data);
$this->load->view('User/template/footer');
return true;
}else
{
$this->load->view('User/template/header');
$this->load->view('User/template/navigator');
$this->load->view('User/landingpagefail');
$this->load->view('User/template/footer');
return false;
}
}
VIEW:
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-body">
<?php if($info) : foreach($info as $u_info) : ?>
<ul class="list-unstyled">
<li>Last Name : <?php echo $u_info->uid; ?></li>
<li>First Name : <?php echo $u_info->userFirstname; ?></li></li>
<li>Middle Name : <?php echo $u_info->userMiddlename; ?></li></li>
<li>Course : <?php echo $u_info->userCourse; ?></li></li>
</ul>
<?php endforeach; ?>
<?php else :?>
<h4> No Record Found</h4>
<?php endif; ?>
</div>
</div>
</div>
Rewrite your model function as
function userdisplay_info($id){
$this->db->select('uid');
$this->db->like('userIdentificationNumber', $id);
$query = $this->db->get('user');
return $query->result_array();
}