My aim is to delete a row whenever I click delete button. My method doing this is by passing the value of ['movies_id'] and storing it inside a hidden input and then passing it when delete button is pressed. The issue is that when I press the delete button it only reads the first id, which in this case is 1. Even though I press the delete button in the 3 card for example. So, my question is how do I pass the correct 'movies_id' stored inside 'keyToDelete' so that it doesn't always read 1?
As you can see in the image below, the id from mysql is being read well inside the card.
function displayMovies()
{
global $dbc;
$movieSelect = "SELECT * FROM movies_tbl";
$query = mysqli_query($dbc, $movieSelect);
if (mysqli_num_rows($query) == 0) {
echo "There is nothing to display.";
} else {
$edit = "";
$delete = "";
if (isset($_SESSION['type'])) {
if ($_SESSION['type'] == "admin") {
$edit = "<a href='#' class='btn btn-cyan align-self-end'>Edit</a>";
$delete = '<input type = "submit" name="delete" value="Delete" form="movieForm" class="btn btn-cyan align-self-end">';
while ($row = mysqli_fetch_assoc($query)) {
movieDesc($row['movies_id'], $row['movie_title'], $row['main_actor'], $row['movie_length'], $row['average_rating'], $row['release_date'], $row['description'], $row['img_path'], $row['trailer_url'], $edit, $delete);
}
} else if ($_SESSION['type'] == "user") {
while ($row = mysqli_fetch_assoc($query)) {
movieDesc($row['movies_id'],$row['movie_title'], $row['main_actor'], $row['movie_length'], $row['average_rating'], $row['release_date'], $row['description'], $row['img_path'], $row['trailer_url'], $edit, $delete);
}
}
} else {
for ($i = 1; $i < 4; $i++) {
$row = mysqli_fetch_assoc($query);
movieDesc($row['movies_id'],$row['movie_title'], $row['main_actor'], $row['movie_length'], $row['average_rating'], $row['release_date'], $row['description'], $row['img_path'], $row['trailer_url'], $edit, $delete);
}
}
}
}
if (isset($_POST['delete'])){
$key = $_POST['keyToDelete'];
echo"<h1>$key</h1>";
}
function movieDesc($movies_id,$movie_title, $main_actor, $movie_length, $average_rating, $release_date, $description, $img_path, $trailer_url, $edit, $delete)
{
echo '<div class="col-md-4 mb-4">
<div class="card">
<img src="images/' . $img_path . '.jpg" class="card-img-top cardImage">
<div class="card-body d-flex flex-column">
<form action="movies.php" id="movieForm" method="post">
<h3 class="card-title text-center fontEDO">' . $movie_title, $movies_id . '</h3>
<div class="row">
<div class="col">
<p class="card-text text-left"><b>Main Actor:</b></p>
<p class="card-text text-left"><b>Movie Length:</b></p>
<p class="card-text text-left"><b>Average Rating:</b></p>
<p class="card-text text-left"><b>Release Date:</b></p>
</div>
<div class="col">
<p class="card-text text-left">' . $main_actor . '</p>
<p class="card-text text-left">' . $movie_length . '</p>
<p class="card-text text-left">' . $average_rating . '</p>
<p class="card-text text-left">' . $release_date . '</p>
</div>
</div>
<p class="card-text text-left description"><br><b>Description:</b> ' . $description . '</p>
<input type="text" name="keyToDelete" value='. $movies_id .'>
</form>
<div class="mt-auto text-center">
Watch Trailer
' . $edit . '
' . $delete . '
</div>
</div>
</div>
</div>';
}
You can't have duplicate id="movieForm". When you use form="movieForm" in the submit button, it submits the first form with that ID, not the one just before the button.
You should move the submit button inside the form, and get rid of form="movieForm" from the button.
Or give each form a unique ID, and use that in the form attribute of the submit button.
Related
I have this piece of code regarding a carousel. I need the first card to have the "active" class but not the following ones or the carousel wont slide. How can i do that?
Here's my code...
$sql = "select wine.wine_name, wine.id, wine.wine_img,
region.region_name, winetype.winetype_name from wine, region, winetype
where wine.region_id = region.id and wine.winetype_id = winetype.id
and sponsored = 1;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div class="carousel-item col-md-4 active">
<div class="card align-items-center">
<img class="card-img-top img-fluid " src='.$row["wine_img"].' alt="Card image cap">
<div class="card-body">
<h4 class="card-title">'.$row["wine_name"].'</h4>
<p class="card-text">'.$row["winetype_name"].' - '.$row["region_name"].'</p>
</div>
</div>
</div>';
}
} else {
echo "ERRO!";
}
you can use a counter to set the active class.
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$count_results = 0;
while($row = $result->fetch_assoc()) {
echo '<div class="carousel-item col-md-4 ' . ($count_results == 0 ? 'active' : '') . '">
<div class="card align-items-center">
<img class="card-img-top img-fluid " src='.$row["wine_img"].' alt="Card image cap">
<div class="card-body">
<h4 class="card-title">'.$row["wine_name"].'</h4>
<p class="card-text">'.$row["winetype_name"].' - '.$row["region_name"].'</p>
</div>
</div>
</div>';
$count_results++;
}
} else {
echo "ERRO!";
}
You could just have a field with the extra class part set to active and then reset it at the end of the loop...
// output data of each row
$class = ' active';
while($row = $result->fetch_assoc()) {
echo '<div class="carousel-item col-md-4' .$class. '">
<div class="card align-items-center">
<img class="card-img-top img-fluid " src='.$row["wine_img"].' alt="Card image cap">
<div class="card-body">
<h4 class="card-title">'.$row["wine_name"].'</h4>
<p class="card-text">'.$row["winetype_name"].' - '.$row["region_name"].'</p>
</div>
</div>
</div>';
$class = '';
}
This should do the trick:
while($row = $result->fetch_assoc()) {
$active = isset($active) ? '' : 'active';
echo '<div class="carousel-item col-md-4 ' . $active . '">
...
}
The variable $active will only be unset (undefined or null) on the first iteration. Then, on the other iterations, the variable will be defined and not null (since it's an empty string) so then we simply set it as an empty string again.
I would make a counter and simply check if you need to add the class. Of course, since you only need it once, you can use a boolean.
<?php
$sql = "select wine.wine_name, wine.id, wine.wine_img,
region.region_name, winetype.winetype_name from wine, region, winetype
where wine.region_id = region.id and wine.winetype_id = winetype.id
and sponsored = 1;";
$result = $conn->query($sql);
?>
<?php if ($result->num_rows > 0): ?>
<?php $first = true; ?>
<?php while ($row = $result->fetch_assoc()): ?>
<div class="carousel-item col-md-4 <?= $first ? 'active' : '' ?>">
<div class="card align-items-center">
<img class="card-img-top img-fluid " src=<?= $row["wine_img"] ?> alt="Card image cap">
<div class="card-body">
<h4 class="card-title"><?= $row["wine_name"] ?></h4>
<p class="card-text"><?= $row["winetype_name"] ?> - <?= $row["region_name"] ?></p>
</div>
</div>
</div>
<?php $first = false; ?>
<? endwhile; ?>
<?php else: ?>
<span>Error!</span>
<?php endif; ?>
I've also taken the liberty of taking all of your HTML out of the single echo. This is much cleaner :)
I'm working on a Content Management System using PHP for controlling over my Telegram Bot. Basically what I have done till now is that I can read the messages that people has sent to my Telegram Bot and answer to them.
In order to do that, I coded this:
<?php
$botToken = '423495534:asdsadsadasdsadsa';
$website = 'https://api.telegram.org/bot'.$botToken;
$update = file_get_contents($website."/getUpdates");
$updateArray = json_decode($update, TRUE);
$info = file_get_contents($website."/getme");
$infoArray = json_decode($info, TRUE);
$num = count($updateArray["result"]);
$sender_ids = array();
$sender_infos = array();
for($i=0;$i<$num;$i++){
$sender_id = $updateArray["result"][$i]["message"]["from"]["id"];
$sender_isbot = $updateArray["result"][$i]["message"]["from"]["is_bot"];
$sender_fname = $updateArray["result"][$i]["message"]["from"]["first_name"];
$sender_lname = $updateArray["result"][$i]["message"]["from"]["last_name"];
$sender_uname = $updateArray["result"][$i]["message"]["from"]["username"];
$sender_type = $updateArray["result"][$i]["message"]["chat"]["type"];
$sender_msg = $updateArray["result"][$i]["message"]["text"];
$sender_date = $updateArray["result"][$i]["message"]["date"];
if(false === $key = array_search($sender_id, $sender_ids)){
$sender_ids[] = $sender_id;
$sender_infos[] = [
'sender_id' => $sender_id,
'sender_isbot' => $sender_isbot,
'sender_fname' => $sender_fname,
'sender_lname' => $sender_lname,
'sender_uname' => $sender_uname,
'sender_type' => $sender_type,
'sender_msg' => [$sender_msg],
'sender_date' => [$sender_date]
];
}else{
$sender_infos[$key]['sender_msg'][] = $sender_msg;
$sender_infos[$key]['sender_date'][] = $sender_date;
}
}
$num2 = count($sender_ids);
for($j=0;$j<$num2;$j++){
$id = $sender_infos[$j]["sender_id"];
$first_name = $sender_infos[$j]["sender_fname"];
$last_name = $sender_infos[$j]["sender_lname"];
$username = $sender_infos[$j]["sender_uname"];
$messages = $sender_infos[$j]["sender_msg"];
$acc_type = $sender_infos[$j]["sender_type"];
$isbot = $sender_infos[$j]["sender_isbot"];
$num1 = count($messages);
echo '
<div class="col-md-3">
<div class="box box-danger direct-chat direct-chat-danger">
<div class="box-header with-border">
<h3 class="box-title">'.$first_name.'</h3>
<sup>'.$acc_type.' - '.$isbot.'</sup>
<div class="box-tools pull-right">
<span data-toggle="tooltip" title="'.$num1.' New Messages" class="badge bg-red">'.$num1.'</span>
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
<button type="button" class="btn btn-box-tool" data-toggle="tooltip" title="Contacts" data-widget="chat-pane-toggle">
<i class="fa fa-comments"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
</div>
</div>
<div class="box-body">
<div class="direct-chat-messages">
<div class="direct-chat-msg">
<div class="direct-chat-info clearfix">
<span class="direct-chat-name pull-left">';
echo '<strong>'.$first_name.'</strong>';
echo '
</span>
</div>';
for($i=0;$i<$num1;$i++){
echo '<div class="direct-chat-text">';
$text = $sender_infos[$j]["sender_msg"][$i];
if($text[0] === '/') {
echo ''.$text.'';
}else{
echo $text;
}
echo '<span class="direct-chat-timestamp pull-right">';
// echo date('l', $sender_infos[$j]["sender_date"][$i]);
echo '</span>';
echo '</div>';
}
echo '
</div>
<div class="direct-chat-msg right">
<div class="direct-chat-info clearfix">
<span class="direct-chat-name pull-right">'.$bot_fname.'</span>
</div>
<img class="direct-chat-img" src="
';
if ($dataSet->GetAvatar() != NULL){
echo $dataSet->GetAvatar();
}else{
echo "img/noprofilepic.jpg";
}
echo '
" alt="Message User Image">
';
$num3 = count($request_params["text"]);
foreach($_SESSION['messages'] as $reply){
echo '<div class="direct-chat-text">';
echo $reply;
echo '</div>';
}
echo '
</div>
</div>
<div class="direct-chat-contacts">
<ul class="contacts-list">
<li>
<a href="#">
<div class="contacts-list-info">
<span class="contacts-list-name">
';
echo $first_name = $sender_infos[$j]["sender_fname"];
echo ' </br> ';
echo $last_name = $sender_infos[$j]["sender_lname"];
echo ' </br> ';
echo ' <a target="_blank" href="http://www.t.me/'.$username.'">'.$username.'</a>';
echo ' </br> ';
echo ' <small class="contacts-list-date pull-right">'.$id.'</small>
</span>
<span class="contacts-list-msg">QUOTE</span>
</div>
</a>
</li>
</ul>
</div>
</div>';
if (isset($_POST['send'])){
$pm = $_POST['message'];
array_push($_SESSION['messages'], $pm);
$request_params = [
'chat_id' => $id,
'text' => $pm
];
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=telegrambots.php?user_name=".$user_name."'>";
$request_url = 'https://api.telegram.org/bot' . $botToken . '/sendMessage?' . http_build_query($request_params);
$response = file_get_contents($request_url);
}
echo '
<div class="box-footer">
<form action="" method="post">
<div class="input-group">
<input type="text" name="message" placeholder="Write your direct message" class="form-control">
<span class="input-group-btn">
<input name="send" type="submit" class="btn btn-danger btn-flat"/>
</span>
</div>
</form>
</div>
</div>
</div>
';
}
?>
Basically what it does is that it grabs the latest updates of my Bot and count the number of results and save it in $num. Then with a for loop I tried to divide every information about the user who has sent message. After that I store all the required information of sender in a separated array called $sender_infos. And the next for loop shows a basic Chat Box depending on the number of users.
This whole thing makes this:
So it works fine and perfect but the problem is that, whenever I try answering to one conversation, it sends the message to all the available users. This issue comes from the for loop which divides every users by the Chat Box.
However what I want to do is to send a SINGLE DIRECT MESSAGE to a CUSTOM user and NOT ALL OF THEM.
I hope I have explained my problem well, so you could understand. If not, please comment me for more information and additional updates.
NOTE: I don't want a quick answer to this question. Because I'm facing this for several days and I don't know how to solve it. Please make sure you understand what I'm asking for and then add your suggest.
Thanks in advance...
I need tips or direction on how can I display data from mysql using echo. But I want to display it in html code. I want to display $row["title"] of first title in mysql instead title1 and $row["content"] of first content in mysql instead content1 and do that for all 3 divs. php code works fine I just can't figure out how to make that possible.
<div class="carousel-inner" style="background-size:cover;">
<div class="item active">
<img src="img/road1.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>title1</h2>
<p>content1</p>
</div>
</div>
<div class="item">
<img src="img/road2.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>title2</h2>
<p>content2</p>
</div>
</div>
<div class="item">
<img src="img/road3.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>title3</h2>
<p>content3</p>
</div>
</div>-->
<?php
session_start();
include_once("db.php");
$sql = "SELECT * FROM news";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_assoc($query)) {
echo "<h2>" . $row["title"] . "</h2>";
echo "<p>" . $row["content"] . "</p>";
}
} else {
echo "0 results";
}
?>
You're almost there. Just move the html into the echo of the while loop.
echo '<div class="carousel-inner" style="background-size:cover;">';
$counter = 1;
while($row = mysqli_fetch_assoc($query)) {
echo '
<div class="item ' . ($counter == 1 ? 'active' : '') . '">
<img src="img/road{$counter}.jpg">
<div class="carousel-caption d-none d-md-block">
<h2>' . $row["title"] . '</h2>
<p>' . $row["content"] . '</p>
</div>
</div>';
$counter++;
}
echo '</div>';
The only issue is the image, realistically you'd save the image in the database with the title and content then use the same method but for this simple case lets just use a counter
please note that I change your entire code a little bit to make the desired results...
<div class="carousel-inner" style="background-size:cover;">
<?php
session_start();
include_once("db.php");
$sql = "SELECT * FROM news";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_assoc($query)) { ?>
<div class="item active">
<img src="img/road1.jpg">
<div class="carousel-caption d-none d-md-block">
<h2><?php echo $row["title"]; ?></h2>
<p><?php echo $row["content"]; ?></p>
</div>
</div>
<?php
}
} else {
echo "0 results";
}
?>
Also note that I'm repeating just the first image... You need an extra on planning to determine how to handle images in code and then update this one.
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
Let me start by apologizing for the information overload. I have no idea what is not working, so I included a little of everything here.
I have a page named jobs.php that shows a table of open 'jobs' on the left side. When the add job button is clicked, the form to add a new job is loaded into the div on the right side of the page using this:
//Get Next Job
$query = "SELECT * FROM jobs WHERE job_id = (SELECT MAX(job_id) FROM jobs)";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
$topjob = $result->fetch_assoc();
$nxtjob = $topjob['job_id'] + 1;
<button class="btn btn-primary pull-right ajaxCall" id="addJobBtn" onclick="nxtJob('<?php echo $nxtjob; ?>')">Add Job</button>
function nxtJob(job) {
var nxtjob = job;
$("#jobDetails").html("Loading...");
$.ajax({
type: "GET",
data: {'id':nxtjob},
url: "addjob.php",
async: true,
success: function(data) {
$("#jobDetails").html(data);
}
});
}
The reasoning behind the get variable is that I need the next job # to be used as a value in the form.
The form itself is on addjob.php, and the very simplified version is this:
<?php
require 'database.php';
if (isset($_POST['addNewJob'])) {
$error = '';
//Check Job # for duplicate if manually changed
$job = $_POST['addjob'];
$query = "SELECT job_id from jobs WHERE job_id = '$job'";
$result = $mysqli->query($query) or die($mysqli->error . __LINE__);
if (mysqli_num_rows($result) > 0) {
$error .= '<br/>Job # already exists.'
}
if ($error == '') {
//Set variables for insert
$job = $mysqli->real_escape_string($_POST['addjob']);
$status = $mysqli->real_escape_string($_POST['addstatus']);
$sql = "INSERT INTO jobs (job_id, status)
VALUES ('$job', '$status')";
if (mysqli_query($mysqli, $sql)) {
$validation = '< div class="alert alert-success" > Job ' . $job . ' Successfully Added </div >';
} else {
$validation = '<div class="alert alert-danger" > "ERROR: Could not able to execute' . $sql . mysqli_error($mysqli);
}
} else {
$validation = ' <div class="alert alert - danger">Job Not Added:' . $error . '</div>';
}
?>
<form class="form - horizontal" method="post" id="addJobForm">
<div class="form - group">
<label for="addjob" class="col - sm - 2 control - label">Job #</label>
<div class="col - sm - 4">
<input type="text" class="form - control" name="addjob"
value=" <?php echo $nxtjob; ?>">
</div>
<label for="addstatus" class="col-sm-2 control-label">Status</label>
<div class="col-sm-4">
<?php
$options = array("New", "In Progress", "Waiting for Parts", "Ready for Customer", "Completed");
?>
<select class="form-control" name="addstatus">
<?php foreach ($options as $option): ?>
<option>
<?php echo $option; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<button type="submit" name="addNewJob" id="addNewJob" class="btn btn-primary pull-right">Submit New
Job
</button>
</form>
<?php echo $validation; ?>
When the add job button is clicked on jobs.php (below), the form loads beautifully, but it doesn't work.
<div class="row">
<div class="col-md-4">
<table class="table table-hover" id="jobTable" data-link="row">
<thead>
<tr>
<th class="col-md-2">Job #</th>
<th class="col-md-4">Customer Name</th>
<th class="col-md-6">Description</th>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($jobs)) {
// Print out the contents of the entry
date_default_timezone_set('America/Los_Angeles');
$startdate = date("m/d/Y", strtotime($row['started']));
echo '<tr>';
echo '<td><a class="ajaxCall" href="#" rel="' . $row['job_id'] . '"></a>' . $row['job_id'] . '</td>';
echo '<td>' . $row['cust_name'] . '</td>';
echo '<td class="col-lg-2">' . $row['description'] . '</td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<div class="col-md-8">
<div id='jobDetails'></div>
</div>
</div>
When I click Submit New Job, the right side of the page simply goes blank. The form disappears, and no new entry is created in the sql table. However, the form works just fine if I use it directly from addjob.php.
I've read about binding after an AJAX call, and I'm guessing it has something to do with that, but I can't seem to get it working. This is my first attempt at AJAX, so any help is appreciated.