I'm trying to modify the contents of a cell in a table with php and ajax.
the problem that the content has been changed in the page but it is not registered in the database.
this is the page index.php:
<?php
include 'connexion.php';
$sql = 'SELECT * FROM liste_user_tbl';
$result = mysql_query($sql) or die(__LINE__.mysql_error().$sql);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Modification "inline" de données</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script>
$(function(){
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('test1.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
setTimeout(function(){message_status.hide()},3000);
}
});
});
</script>
</head>
<body>
<h1>Utilisateurs</h1>
<table id="table-utilisateurs">
<tr>
<th>Nom</th>
<th>Prénom</th>
</tr>
<?php
while($user = mysql_fetch_assoc($result))
{
?>
<tr>
<td id="<?php echo $user['id']; ?>" contenteditable="true">
<?php echo $user['nom']; ?>
</td>
<td id="<?php echo $user['id']; ?>" contenteditable="true">
<?php echo $user['prenom']; ?>
</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
<?php
mysql_close();
?>
this is test1.php:
<?php
if(!empty($_POST))
{
include "connexion.php";
foreach($_POST as $field_name => $val)
{
//clean post values
$field_userid = strip_tags(trim($field_name));
$val = strip_tags(trim(mysql_real_escape_string($val)));
//from the fieldname:user_id we need to get user_id
$split_data = explode(':', $field_userid);
$user_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($user_id) && !empty($field_name) && !empty($val))
{
//update the values
mysql_query("UPDATE liste_user_tbl SET $field_name = '$val' WHERE id = $user_id") or mysql_error();
echo "Updated";
} else {
echo "Invalid Requests";
}
}
} else {
echo "Invalid Requests";
}
?>
this is my table :
First of all, $field_name is not defined in your code, that's why the query will produce an error if you enable debugging
Second of all, your code is very vulnerable to SQL injections. Your are using user's posted data as it is, without any filtering, and this can lead to loosing your entire database data.
Third of all, you are still using procedural php and "old schoool" database connection. Instead, you can use PDO and POO
use
print_r($_POST);
to receive post data and display
check if the post data has a problem
Related
I have orders table in my database that has id,name and status columns.Then i have html table representing my orders table and inside i have
buttons that i want to update the status column using ajax to make it asynchronous displaying the changes in the html table rigth away.How can i
achieve this?I have tried running ajax functions onclick of a button passing order id as an argument and then using get method to fetch the result but
something is wrong with the document.getElementsByClassName method it is not populating my status field in the html table nor the database is being changed.
orders.php
$query=mysqli_query($conn,"SELECT*FROM orders");
echo "<table border='1'>";
echo "<th>Id</th><th>Name</th><th>Status</th><th>Considering</th><th>Accepted</th>";
while($row=mysqli_fetch_array($query)){
$id=$row['id'];
$name=$row['name'];
$status=$row['status'];
echo "<tr>
<td>$id</td><td>$name</td><td><div class='status'>$status</div></td><td><buttton onclick=\"considering('$id')\">Considering</button></td>
<td><buttton onclick=\"accepted('$id')\">Accepted</button></td>
</tr>";
}
admin.php
<?php
include "include/connect.php";
?>
<!DOCTYPE html>
<html>
<head>
<script>
function considering(one){
var a=new XMLHttpRequest();
a.open("GET","considering_parser.php?one="+one,true);
a.onreadystatechange=function(){
if(a.readyState==4 && a.status==200){
var returndata=a.responseText;
var x=document.getElementsByClassName("status");
for(var i=0;i<x.length;i++){
x[i].innerHTML=returndata;
}
}
}
a.send(null);
}
function accepted(two){
var b=new XMLHttpRequest();
b.open("GET","accepted_parser.php?two="+two,true);
b.onreadystatechange=function(){
if(b.readyState==4 && b.status==200){
var returndata=b.responseText;
var x=document.getElementsByClassName("status");
for(var i=0;i<x.length;i++){
x[i].innerHTML=returndata;
}
}
}
b.send(null);
}
</script>
</head>
<body>
<div id="content">
<?php
include "orders.php";
?>
</div>
</body>
</html>
considering_parser.php
<?php
include "include/connect.php";
$id=$_GET['one'];
$query=mysqli_query($conn,"UPDATE orders SET status=1 WHERE id='$id'");
$query=mysqli_query($conn,"SELECT * FROM orders WHERE id='$id'");
while($row=mysqli_fetch_array($query)){
$one=$row['status'];
echo $one;
}
?>
accepted_parser.php
<?php
include "include/connect.php";
$id=$_GET['two'];
$query=mysqli_query($conn,"UPDATE orders SET status=2 WHERE id='$id'");
$query=mysqli_query($conn,"SELECT * FROM orders WHERE id='$id'");
while($row=mysqli_fetch_array($query)){
$two=$row['status'];
echo $two;
}
?>
Help would be appreciated
Ok i solved it thanks to Fred-ii's suggestion to use multi_query()
orders.php
$query=mysqli_query($conn,"SELECT*FROM orders");
echo "<table border='1'>";
echo "<th>Id</th><th>Name</th><th>Status</th><th>Considering</th><th>Accepted</th>";
while($row=mysqli_fetch_array($query)){
$id=$row['id'];
$name=$row['name'];
$status=$row['status'];
echo "<tr>
<td>$id</td><td>$name</td><td><div class='status$id'>$status</div></td><td><buttton onclick=\"considering('$id')\">Considering</button></td>
<td><buttton onclick=\"accepted('$id')\">Accepted</button></td>
</tr>";
}
admin.php
<html>
<head>
<script>
function considering(one){
var a=new XMLHttpRequest();
a.open("GET","considering_parser.php?one="+one,true);
a.onreadystatechange=function(){
if(a.readyState==4 && a.status==200){
var returndata=a.responseText;
var x=document.getElementsByClassName("status"+one);
for(var i=0;i<x.length;i++){
x[i].innerHTML=returndata;
}
}
}
a.send(null);
}
function accepted(two){
var b=new XMLHttpRequest();
b.open("GET","accepted_parser.php?two="+two,true);
b.onreadystatechange=function(){
if(b.readyState==4 && b.status==200){
var returndata=b.responseText;
var x=document.getElementsByClassName("status"+two);
for(var i=0;i<x.length;i++){
x[i].innerHTML=returndata;
}
}
}
b.send(null);
}
</script>
</head>
<body>
<div id="content">
<?php
include "orders.php";
?>
</div>
</body>
</html>
considering_parser.php
<?php
include "include/connect.php";
$id=$_GET['jedan'];
$query="UPDATE orders SET status=1 WHERE id='$id';
SELECT * FROM orders WHERE id='$id';";
if (mysqli_multi_query($conn,$query))
{
do
{
// Store first result set
if ($result=mysqli_store_result($conn))
{
while ($row=mysqli_fetch_array($result))
{
$one=$row['status'];
echo $one;
}
}
}
while (mysqli_more_results($conn) && mysqli_next_result($conn));
}
mysqli_close($conn);
?>
Similar code for the accepted_parser.php.Thank you Fred-ii
I have a mySQL database that is queried and displayed in tables in index.php. I have a file called up.php that handles a click on an < a > in each table that is output from the query in index.php. I need to have a variable that I can extract from a field in each seperate row that is queried, so that when the < a > is clicked it passes the variable to the up.php file to be manipulated. Right now the variable is just being over written and is equal to the value of the last row queried and the database is updated frequently, so I can't just set one to each row, it has to be dynamic.
Here is the index.php file
<?php
$sql = mysql_query("SELECT * FROM blogData ORDER BY id DESC");
//query for even numbered rows where mes_id = even
$sql2=mysql_query("SELECT * FROM messages WHERE mod(mes_id,2) = 0 ORDER BY mes_id DESC");
//query for odd numbered rows where mes_id = even
$sql3=mysql_query("SELECT * FROM messages WHERE mod(mes_id,2) = 1 ORDER BY mes_id DESC");
while(($row = mysql_fetch_array($sql))AND($row2 = mysql_fetch_array($sql2))AND($row3 = mysql_fetch_array($sql3)) ){
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$category = $row['category'];
$podcast = $row['podcast'];
$datetime = $row['datetime'];
$message1=$row2['msg'];
//******* this is the variable from the query that needs to be held and not overwritten ********
$mes_id1=$row2['mes_id'];
$totalvotes1=$row2['totalvotes'];
$message2=$row3['msg'];
//******* this is the second variable from the query that needs to also be held and not overwritten *******
$mes_id2=$row3['mes_id'];
$totalvotes2=$row3['totalvotes'];
//attempting to implement this array...? not sure how to use it correctly...
$valuess[]=$row2['mes_id'];
//******* I was trying to use these session variables in up.php but they were being overwritten in the query ********
$_SESSION['message1'] = $row2['msg'];
$_SESSION['message2'] = $row3['msg'];
$_SESSION['mes_id1'] = $row2['mes_id'];
$_SESSION['mes_id2'] = $row3['mes_id'];
$_SESSION['totalvotes1'] = $row2['totalvotes'];
$_SESSION['totalvotes2'] = $row3['totalvotes'];
$_SESSION['valuess'] = $valuess[1];
?>
<?php
// variable used to display file name of $podcast without the extension
$noext = $podcast;
$echodub = rawurlencode($podcast);
// code to display $noext without the file extension
$info = pathinfo($noext);
$noext_name = basename($noext,'.'.$info['extension']);
?>
<!-- ********* echo php variables in html format, in a table with the class of "podcast" -->
<table class="podcast" border="1">
<tr>
<td class="title">
<?php echo $title; ?>
</td>
<td class="timeandcategory">
<?php echo $datetime; ?> <br>
<?php echo $category; ?>
<?php echo $_SESSION['mes_id1']; ?>
<?php echo $_SESSION['mes_id2']; ?>
<?php echo session_id(); ?>
</td>
</tr>
<tr>
<td class="content">
<?php echo $content; ?>
</td>
<td class="myfblike">
<span class='st_fblike_large' displayText='Facebook Like'></span><br>
<span class='st_facebook_large' displayText='Facebook'></span><br>
<span class='st_twitterfollow_large' displayText='Twitter Follow'></span><br>
<span class='st_pinterest_large' displayText='Pinterest'></span><br>
<span class='st_email_large' displayText='Email'></span><br>
<span class='st_sharethis_large' displayText='ShareThis'></span><br>
</td>
</tr>
<tr>
<td class="audio">
<!--echo the audio file -->
<ul class="playlist">
<li><?php echo"$noext_name"; ?></li>
</ul>
</td>
<td>
<!-- ********** this is the cell in the table where the veriables need to be held and sent to up.php ******** -->
<div id="main">
<div id="left">
<span class='up'><img src="up.png" alt="Down" /></span><br />
<?php echo $_SESSION['totalvotes1'] ?><br />
</div>
<div id="message">
<?php echo $_SESSION['message1'] ?>
</div>
<div class="clearfix"></div>
</div>
//********the down.php file is the same as the up.php file... just with opposite variables... im not concerned with this yet until i get the variables to display correctly in up.php
<div id="main">
<div id="left">
<br />
<?php echo $_SESSION['totalvotes2'] ?><br />
<span class='down'><img src="down.png" alt="Down" /></span>
</div>
<div id="message">
<?php echo $_SESSION['message2'] ?>
</div>
<div class="clearfix"></div>
</div>
</td>
</tr>
</table>
<br>
<?php
}
?>
and here is the up.php file
up.php
<?php
session_start();
include("config.php");
$message1 = $_SESSION['message1'];
$message2 = $_SESSION['message2'];
$mes_id1 = $_SESSION['mes_id1'];
$mes_id2 = $_SESSION['mes_id2'];
$totalvotes1 = $_SESSION['totalvotes1'];
$totalvotes2 = $_SESSION['totalvotes2'];
$ip=$_SERVER['REMOTE_ADDR'];
$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$mes_id1' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
$ip_sql2=mysql_query("select ip_add from Voting_IP where mes_id_fk='$mes_id2' and ip_add='$ip'");
$count2=mysql_num_rows($ip_sql2);
//********* testing if these variables are being passed.....
echo $mes_id1;
echo $mes_id2;
$valuess[0] = $_SESSION['valuess'];
echo $valuess[0];
//********
// if the user has already voted, execute script
if($count==0 && $count2!=0)
{
$sql = "update Messages set totalvotes=totalvotes+1 where mes_id='$mes_id1'";
mysql_query( $sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$mes_id1','$ip')";
mysql_query( $sql_in);
$sql = "update Messages set totalvotes=totalvotes-1 where mes_id='$mes_id2'";
mysql_query( $sql);
$sql_in = "DELETE FROM Voting_IP WHERE mes_id_fk='$mes_id2'";
mysql_query( $sql_in);
// if the user has not voted, execute script
}
else if($count==0 && count2==0)
{
$sql = "update Messages set totalvotes=totalvotes+1 where mes_id='$mes_id1'";
mysql_query( $sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$mes_id1','$ip')";
mysql_query( $sql_in);
echo $mes_id1;
echo $mes_id2;
}
?>
Thank you so much to anybody who is able to help me!
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
} });
}
else
{
$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "down.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
});
});
With the javascript, I can see what you need to do in order to get it working how you want.
Instead of putting the key1=value1 etc attached to the href, put it in its own attribute called data-options, without the ? pre-pending it. So looking like:
Up/Down
From there, you would modify the JS to be:
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);
From there, you would access them in the up.php and down.php files by using $_POST['key1'], and only need to echo out what your JS is expecting in return from its AJAX call. ^^
I am developing a simple students information application. I have student list in my index.phtml and I can edit student information form there. It's working nice but I want to use modal for edition student info. But I don't know how to do this.Below I have posted my current codes :
/// indexController.php
public function editAction()
{
$modelStudents = new Application_Model_DbTable_Students();
$id = (int) $this->_getParam('id');
$student = $modelStudents->fetch($id);
$form = new Application_Form_Student($student->email);
$form->submit->setLabel('Save');
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$id = (int)$form->getValue('id');
$name = $form->getValue('name');
$email = $form->getValue('email');
$phone = $form->getValue('phone');
$students = new Application_Model_DbTable_Students();
$students->updateStudent($id, $name, $email, $phone);
$this->_helper->redirector('index');
} else {
$form->populate($formData);
}
} else {
$id = $this->_getParam('id', 0);
if ($id > 0) {
$form->populate($modelStudents->getStudent($id));
}
}
}
/// index.phtml
<html>
<head>
<style type="text/css" rel="stylesheet">
</style>
<script type="text/javascript" src="jQuery.js"> </script>
<script type ="text/javascript" src="jquery.simplemodal-1.4.2.js" ></script>
<script>
<?php
echo "Student List";
?>
<p><a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'add'));?>">Add new student</a></p>
<table border="1">
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Action</th>
</tr>
<?php foreach($this->students as $student) : ?>
<tr>
<td><?php echo $student->name;?></td>
<td><?php echo $student->email;?></td>
<td><?php echo $student->phone;?></td>
<td>
<a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'edit', 'id'=>$student->id));?>">Edit</a>
<a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'delete', 'id'=>$student->id));?>">Delete</a>
<p id="delete" > Delete </p>
</td>
</tr>
<?php endforeach; ?>
</table>
</center>
</html>
////edit.phtml
<center>
<?php
echo "Edit Student List ";
echo $this->form ;
?>
</center>
Please let me know how to use jQuery simple modal plugin to preform this task.
Thanks in advance
Start by editing your index.phtml file to add a class and the student id to your edit link:
<a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'edit', 'id'=>$student->id));?>" class="editBtn" studentId="<?=$student->id?>">Edit</a>
Then, in an included js file:
$(document).ready(function() {
$(function() {
//Event triggered when clicking on the edit btn
$('.editBtn').click(function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
//Get the page and add it to the modal
studentId = $(this).attr('studentId');
var data={};
data['id'] = studentId;
url = "/index/edit/";
$.get(url, data, function(resp) {
$.modal(resp);
});
});
});
});
This should help you get started...
Hi i am a beginner i am working on software site. i have built all the pages and layout for the site that was the easy part done using HTML CSS AND JAVASCRIPT alone, only thing left is to make main categories pages for different software which is tough for me.
i want to to add sorting option on category pages like this (See Here)
where user shall be able to sort software according to date, name, date added etc. and also be able to control max number of software to display like 20, 30, 100 etc.
On my HTML Page i have these div's in which i want to display data (different softwares)
from MySQL database "security_software" (it is a testing database) from table "internet_security" (it is a testing table)
HTML Div's
<div class="category-container">
<div class="category-image"></div>
<div class="category-desc">#<p>text</p></div>
<div class="rating5" >Editors' rating: </div>
<div class="category-download-btn">Download</div>
<div class="category-buy-btn">Buy</div>
</div>
After Some research i have got a solution to use JSON AJAX PHP &MySQL
JAVASCRIPT Code i have
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$.ajax({
url: 'ajax.php',
dataType: 'json',
success: function(response){
data = '';
$.each(response,function(i,val){
data = '<div class="category-image">'+val.image+'</div>'+
'<div class="category-link">'+val.id+'</div>'+
'<div class="category-desc"><p>'+val.description+'</p> </div>'+
'<div class="rating5" >'+val.rating+'</div>'+
'<div class="category-download-btn">Download</div>'+
'<div class="category-buy-btn">Buy</div>';
$('<div>').attr('id',i).html(data).appendTo('#response');
});
}
});
</script>
</head>
<body>
<div id='response'></div>
</body>
PHP Code i have
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("security_software", $con);
$sql="SELECT * FROM internet_security ORDER by `".$q."` DESC" ;
$result = mysql_query($sql);
$response = array();
$i=0;
while($row = mysql_fetch_array($result))
{
$response[$i]['id'] =$row['id'];
$response[$i]['title'] = $row['title'];
$response[$i]['image'] = $row['image'];
$response[$i]['description'] = $row['description'];
$response[$i]['rating'] = $row['rating'];
$response[$i]['download'] = $row['download'];
$response[$i]['buy'] = $row['buy'];
$i++;
}
mysql_close($con);
echo json_encode($response);
?>
Now it is not working at all as i dont have any place to attach these codes for (categories drop down) in javascript i have.
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="id">id</option>
<option value="title">title</option>
<option value="image">image</option>
<option value="description">description</option>
<option value="description">rating</option>
<option value="download">download</option>
<option value="buy">buy</option>
</select>
</form>
Please help me guys where can i attach these code and how to get it working, i am totally confused.
First thing worth noting is, if you are going to display tabular data... Use a table! It will make things a lot easier for you.
Secondly. Build your code and table as if Ajax did not exist. Initially populate the data using PHP on the page your displaying the data. Then, hook up the column header's so they link to your page, but passing which column you want to sort by and also which direction.
i.e.
<?
$column = (isset($_GET["column"]) ? $_GET["column"] : 'id');
$direction = (isset($_GET['direction']) ? $_GET['direction'] : 'asc');
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("security_software", $con);
$sql="SELECT * FROM internet_security ORDER by '".$column."' " . $direction;
$result = mysql_query($sql);
$response = array();
$i=0;
while($row = mysql_fetch_array($result))
{
$response[$i]['id'] =$row['id'];
$response[$i]['title'] = $row['title'];
$response[$i]['image'] = $row['image'];
$response[$i]['description'] = $row['description'];
$response[$i]['rating'] = $row['rating'];
$response[$i]['download'] = $row['download'];
$response[$i]['buy'] = $row['buy'];
$i++;
}
mysql_close($con);
?>
<div id="content">
<table>
<thead>
<tr>
<td>ID</td>
<td>Title</td>
<td>Rating</td>
<td>Download</td>
</tr>
</thead>
<tbody>
<? foreach($response as $i => $row) : ?>
<tr>
<td><?= $row['id']; ?></td>
<td><?= $row['title']; ?></td>
<td><?= $row['rating']; ?></td>
<td><?= $row['download']; ?></td>
</tr>
<? endforeach; ?>
</tbody>
</table>
</div>
The above code would go inside a single PHP file, without any other HTML etc. Then, on the page you want to display this table, you simply <? include('path-to-file.php'); ?> include it.
Finally... At the top of the page you are displaying the table on, you would put:
<?
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
include('path-to-file.php');
die();
}
?>
The above code would then detect an Ajax request and serve only the table with the data in the new order.
You would then need to use Javascript to replace the table with the new HTML via
$('#content table thead a').live('click', function(e)
{
e.preventDefault();
$.ajax(
{
url : $(this).attr('href'),
success : function(resp)
{
$('#content').html($(resp).html());
},
error : function()
{
alert('There was a problem sorting your table...');
}
});
});
where resp is the variable that contains your Ajax response.
Note: This is just a very simple and crude (oh, and untested) way to handle the situation. You would need to improve it your self to prevent any security related issues such as SQL Injection.
I have a simple table that prints our the list of videos and plays them when you click on the row. I have a delete button to delete the corresponding video in the row. But for some reason when you click on any video it will only delete the last one in the list. I can look at the source on the page and the video_url seems to be correct. Any ideas?
Here is the majority of the code:
<?php
// Dont allow direct linking
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
//get current user
$user =& JFactory::getUser();
// get a reference to the database
$db = &JFactory::getDBO();
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
echo $problem;
}
return $data;
}
if (isset($_POST['delete_video'])) {
$video_url = check_input($_POST['video_url']); //value here is always just the last row in the table!!!
echo $video_url;
$query_delete_video = "DELETE FROM `#__videos` WHERE `video_url`='$video_url'";
$db->setQuery($query_delete_video);
$db->query();
}
//list all details of the camera including camera_name
$query_videos = "SELECT #__videos.video_url, #__videos.video_size, #__videos.video_datetime, #__videos.video_length, #__cameras.camera_name
FROM #__videos INNER JOIN #__cameras using (user_id, camera_id)
WHERE #__videos.user_id=".$user->id." ORDER BY #__videos.video_datetime DESC";
$db->setQuery($query_videos);
//get number of cameras so we can build the table accordingly
$db->query();
$num_videos = $db->getNumRows();
// We can use array names with loadAssocList.
$result_videos = $db->loadAssocList();
echo "<html>";
echo "<head>";
?>
<link href="recordings/recordings.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="flowplayer/example/flowplayer-3.2.6.min.js"> </script>
<?php
echo "</head>";
echo "<body>";
?>
<?php
if (!isset($result_videos))
{
//TODO check if query failed
}
else
{
if ($num_videos == 0)
{
?>
<div id="cc_table">
<table id="webcam-table">
<thead>
<tr>
<th>Camera Name</th>
<th>Camera Details</th>
<th>Video Options</th>
</tr>
</thead>
<td colspan=3><b><i><center>You currently have no videos created. Start monitoring today!</center></i></b></td>
</table>
</div>
<?php
}
else
{
?>
<div id="cc_table">
<form name="myform" action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<table id="webcam-table">
<thead>
<tr>
<th>Camera Name</th>
<th>Camera Details</th>
<th>Video Options</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_videos;$i++)
{
?>
<tr onclick="DoNav('<?php echo $result_videos[$i]["video_url"]; ?>');">
<td>
<?php echo $result_videos[$i]["camera_name"]; ?>
</td>
<td>
Date Created: <?php echo $result_videos[$i]["video_datetime"]; ?> <br>
Video Size: <?php echo $result_videos[$i]["video_size"]; ?> bytes <br>
Video Length: <?php echo $result_videos[$i]["video_length"]; ?> secs
</td>
<td>
<input type="submit" name="delete_video" value="Delete" onClick="return confirm('Are you sure you want to delete?')"/>
</td>
</tr>
<input type="hidden" name="video_url" value="<?php echo $result_videos[$i]["video_url"]; ?>" />
<?php
}
echo "</tbody>";
echo "</table>";
echo "</form>";
echo "</div>";
}
}
?>
<div id="player" style="display:block;width:320px;height:240px;background-image:url(recordings/landscape.jpg)"></div>
<script type="text/javascript">
function DoNav(theUrl)
{
//document.write(document.location.href = theUrl);
flowplayer("player", "flowplayer/flowplayer-3.2.7.swf", theUrl);
}
</script>
<?php
echo "</body>";
echo "</html>";
?>
Can you post the HTML? I suspect you've got multiple hidden input fields on the page, all with the same name. If that's the case, only the last one that loads on the page will register as a valid hidden input. A better way to do it would be to set a data attribute on the delete button, and then add a JS click event to that delete button. Something like this:
<button class="delete" data-video_url="youtube.com/abcd">Delete ABCD</button>
<button class="delete" data-video_url="vimeo.com/xyz">Delete XYZ</button>
and then when someone clicks on a .delete button, you send the data-video_url value to the PHP script via POST. A jQuery example might look like this:
$('.delete').click(function() {
var url = $(this).data('video_url');
$.post('/delete.php', { video_url: video_url }, function() {
// Do something on success
});
});
Another way to do it is to simply make each button its own form:
<form method="post" action="delete.php">
<input type="hidden" name="video_url" value="url_goes_here">
<button>Delete</button>
</form>
Hope that helps. Good luck.
The problem is that the name of the hidden field is not unique (for every iteration in the loop a new hidden field with the same name is created). How should the script know which row you want if all of them has the same name?
Your code does not seem to name the hidden values properly.
You should use $i to name the variable.
input type="hidden" name="video_url<?php echo $i; ?>"
then in handler you can do
<?php
if ($_POST) {
$kv = array();
foreach ($_POST as $key => $value) {
// check here which one begins with video_url
}
}
?>