Can't check which check list is checked - php

I'm trying to delete multiple pictures using checkbox item. But somehow pictures are not deleted from database.
the coderuns without mistake. Page is being redirected but the delete query is not executed.
I believe there is somethong to do with passing picture id to query $List[1] but i really can't understand what.It seems I'm doing everything ok.
Thanks for any help in advance.
That's the code:
<?php
$Connection = mysql_connect( $Host, $User, $Pass ) or die('ERROR: '.mysql_error());
mysql_select_db( $DataBase )or die('ERROR: '.mysql_error());
$Query = "SELECT * FROM pictures WHERE folder_id = ".$FolId.";";
$Picture = mysql_query($Query, $Connection)or die('ERROR: '.mysql_error());
?>
<form name='Photos' method='POST' >
<?php
while($List = mysql_fetch_array($Picture)){
echo "<input type='checkbox' name='photoList[]' value='".$List[1]."'> <span> ".$List[4]."</span>";
}
?>
<input type='submit' name='Delit' value='DELETE' >
</form>
<?php
if(isset($_POST['Delit'])){
foreach($_POST['photoList'] as $item){
$Query="DELETE FROM pictures WHERE picture_id =".$item;
mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
header('Location: photos.php');
}
}
?>

My guess is that $List[1] doesn't contain your picture_id. It's probably $List[0].
Using fetch_array is not a great way to get data from a DB using SELECT *, as your columns may change position, and an index doesn't clearly say which column you're retrieving.
Try using fetch_assoc instead, to get the column names associated with the data.
<?php
// Change `picture_name` below to the name of the column storing your picture's name
while ($List = mysql_fetch_assoc($Picture)) {
echo "<input type='checkbox' name='photoList[]' value='{$List['picture_id']}'> <span> {$List['picture_name']}</span>";
}
?>
Also, try this for your DELETE logic:
Checking if photoList is set (vs. Delit)
Looping through your photo list and casting the values to (int) to prevent SQL Injection
Concatenating the list of IDs into a comma-delimited list using implode
Doing a DELETE... WHERE IN query, providing the photo ID list - this is much faster than looping through and doing several DELETE... WHERE = statements
Code:
<?php
if (isset($_POST['photoList']) && !empty($_POST['photoList'])) {
$photoIds = array();
foreach ($_POST['photoList'] as $photoId) {
$photoIds[] = (int) $photoId;
}
$photoIds = implode(',', $photoIds);
$Query = "DELETE FROM pictures WHERE picture_id IN ({$photoIds})";
mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
header('Location: photos.php');
}
?>

Related

Generate buttons with php that delete or edit a row in a table in db

I need to call database and a specific table, then display table values in rows and at the end of them have buttons 'edit' and 'delete' that allow me to edit that line or delete it completely.
At the moment I only manage to display the table and generate the buttons, but not 'tie' the buttons to that row.
I need to generate the buttons when displaying the table, and then 'tie' the buttons to corresponding row.
Edit:
if(!empty($_POST) && isset($_POST['show'])) {
$sel = "SELECT id, vardas, pavarde, amzius, miestas FROM zmogaus_info";
$res = mysqli_query($conn, $sel);
if(mysqli_num_rows($res)>0){
while($row = mysqli_fetch_assoc($res)){
echo "Id: ".$row["id"]." ".$row["vardas"]." ".$row["pavarde"]." ".$row["amzius"]."m."."<input type='submit' name='".$row['id']."' value='Delete'>"."<br>";
}
}
}
if(!empty($_POST) && isset($_POST[$row['id']])){
$sql = "DELETE FROM zmogaus_info WHERE id=".$row['id'];
mysqli_query($conn, $sql);
}
I think the problem might be with the way I use $row['id'] and i might need to make it into a global variable?
If you are able to var_dump($result) and there is data there from DB, then there is no need for a while loop.
Also research PDO, much safer method of data transfer to and from DB.
$sel = "SELECT id, vardas, pavarde, amzius, miestas FROM zmogaus_info";
$result = $mysqli -> query($sel);
// Define the associative array as $row
$row = $result -> fetch_assoc();
echo "Id: ".$row["id"]." ".$row["vardas"]." ".$row["pavarde"]." ".$row["amzius"]."m."."<input type='submit' name='".$row['id']."' value='Delete'>"."<br>";

How to echo specified data form sql database in php

I need to print data from users table for username that is logged in, for example, need to bring HP, attack, defence, gold... I found many answers here and after this I am sure I am gone ask more questions. Please help...
<?php
session_start()
if(isset($_SESSION['username'])){
echo "Welcome {$_SESSION['username']}";
}
require_once 'config.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("SELECT ID FROM users WHERE UPPER(username) = UPPER('%s')",
mysql_real_escape_string($_SESSION['username']));
$result = mysql_query($query);
list($userID) = mysql_fetch_row($result);
echo "Health Points:".$row['HP'];
echo "Attack:";
echo "Defence:";
echo "Gold:";
?>
You have to query for all the information you actually want. So your query should look like this:
SELECT HP,Atk,Def,Gold FROM ...
This will retrieve the named fields from your database and not just the ID.
Also, you never assign your row, it should read
$row = mysql_fetch_row($result);
(But see my comment below).
1 - there is missing ; in the first line
2 - try "SELECT * " instead of "SELECT ID"
3 - $row is not defined , try :
$row = mysql_fetch_assoc($result);
instead of
list($userID) = mysql_fetch_row($result);
check the manual for the difference between mysql_fetch_row and mysql_fetch_assoc
mysql_fetch_assoc

PHP, resource id# instead of actual string

I have run across a problem during my query service to add a row in an online database in PHP. The addition of the row works just fine. I get user id and book id from the url and fetch the names of the book and the user to put into the row which i add to my third and last table.
When I get the names, put them in an array, json encode it and then echo it, it works. But when I put them in the row it prints resource id#3 and resource id#4 instead of the names.
Any ideas?
Here is my service:
<?php
$con = mysql_connect("localhost","root","root");
$userid=$_GET['uid'];
$id = $_GET['bookid'];
$type = $_GET['type'];
$zero = '0';
$one = '1';
$date = date("Y-m-d");
$arr = array();
if (!$con)
{
die('Could not connect: ' . mysql_error());
echo "error connection";
}
mysql_select_db("Jineel_lib",$con) or die("Could not select database");
$bkName = mysql_query("SELECT Name from books where ID='".$id."'");
$userName = mysql_query("SELECT Name from people WHERE User_ID='".$userid."'");
while($obj = mysql_fetch_object($userName))
{
$arr[] = $obj;
}
echo json_encode($arr);
if($type == 'borrow')
{
$query="UPDATE books set Availablity = '".$zero."' where ID= '".$id."' ";
mysql_query($query) or die (" borrow operation failed due to query 1");
$query1="INSERT into borrowed (BookID, BookName, BorrowerID, BorrowedName, DateBorrowed, Extended, Returned) values('".$id."','".$bkName."','".$userid."','".$userName."','".$date."','".$zer‌​o."','".$zero."')";
mysql_query($query1) or die (" borrow operation failed to due query 2");
echo "borrow success";
}
else if($type=='return')
{
$query="UPDATE books set Availablity = '".$one."' where ID= '".$id."' ";
mysql_query($query) or die (" return operation failed");
$query1="UPDATE borrowed set Returned = '".$one."' where BookID= '".$id."' ";
mysql_query($query1) or die (" return operation failed 1");
echo "return success";
}
else
echo "invalid parameters";
?>
THANK YOU IN ADVANCE
You don't actually retrieve the userName value here:
$userName = mysql_query("SELECT Name...
$userName is just the result resource object returned from the query. You do use mysql_fetch_object later on, which is appropriate, but then you try to use the actual result resource in your insert query:
$query1="INSERT into borrowed ...
It gets converted to the string you see. Instead, you need to use $obj->Name (you fetch the result into $obj, and presumably there is only one result). If there is more than one possible result, you will have to do that in a loop.
Listen to all of the comments on your question.

Inserting Data from dropdown into database with PHP

First I needed a dropdown list that I could update easily so I created a database called
manufacturers where I list manufacturers to be selected in a form.
I finally accomplished this with this code:
<?php
// Connect to the test datbase on localhost
// That's where we created the countries table above
mysql_connect('localhost','##user##','##pass##'); mysql_select_db('wordpress');
// Query the countries table and load all of the records
// into an array.
$sql = 'select * FROM manufacturers';
$res = mysql_query($sql) or die(mysql_error());
while ($rec = mysql_fetch_assoc($res))
$manufacturers[] = $rec;
?>
<form action="select.php" method="post">
<?php
echo '<select name="dropdown">';
foreach ($manufacturers as $c)
{
if ($c['id'] == $_GET['id'])
echo "<option value=\"{$c['meta_id']}\" selected=\"selected\">{$c['meta_value']} </option>\n";
else
echo "<option value=\"{$c['meta_id']}\">{$c['meta_value']}</option>\n";
}
echo '</select>';
?>
<input type="submit" value="Submit" name="submit"/>
</form>
This worked out great I now have a dropdown list that is populated from my
database manufacturers.
Now I need to send this to an existing database call post_meta so that from there I can display the users selection permanently.
I have tried a couple of different options but I am trying to use the following code to send this to my post_meta database.
<?php
$con = mysql_connect("localhost","##user##","##pass##");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordpress", $con);
$sql="INSERT INTO wp_postmeta (meta_id, post_id, meta_key, meta_value)
VALUES
('$_POST['meta_id']}','$_POST[post_id]','$_POST[meta_key]','$_POST[meta_value]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
This actually inserts into the database but doesn't record any values.
Please help me figure out what I'm doing wrong.
The proper way to do this is to A: escape all those $_POST superglobals.
and B. Write a query as shown below.
Here's the tabledef for wp_postmeta:
http://codex.wordpress.org/Database_Description#Table:_wp_postmeta
Because meta_id is an auto_increment primary key, you do not provide it, MySQL does.
//$meta_id = mysql_real_escape_string($_POST['meta_id']); <<-- not needed.
$post_id = mysql_real_escape_string($_POST['post_id']);
$meta_key = mysql_real_escape_string($_POST['meta_key']);
$meta_value = mysql_real_escape_string($_POST['meta_value']);
$sql=" INSERT INTO wp_postmeta
(post_id, meta_key, meta_value)
VALUES
('$post_id','$meta_key','$meta_value') "; //<<-- don't forget the quotes!
if ($result = mysql_query($sql)) {
//You can get the new meta_id using:
$new_meta_id = mysql_insert_id($result);
} else {
die ("could not insert ".mysql_error());
}
Do none of your values show up? It looks like you're missing quotes around your key values. For example, shouldn't it be :
$_POST['post_id']
To do a sanity check, just echo your $_POST variables as opposed to doing the insert right away. This will help you figure out if you've got some syntax wrong. Also I'd read Brad's comment and keep it in mind for the future.
Try this query:
$sql="
INSERT INTO wp_postmeta
(meta_id, post_id, meta_key, meta_value)
VALUES
(
'{$_POST['meta_id']}',
'{$_POST['post_id']}',
'{$_POST['meta_key']}',
'{$_POST['meta_value']}'
)
";
And, as people say in comments, this code is very vulnerable, please consider to find better option to pass variables into query.

PHP and MySQL help needed

I have 2 tables in my database. categories and products. in categories there are 2 fields. catid and catname. and in products also there are 3 fields. id, catid and name.
in my submit form im fetching the catname in to a sector. what i wanna do is get value of the selector and save the catid in to products table catid field. instead of categories name. can anyone explain me how to do this. Thanks in advance.
Here is the code of submit form.
include("db.php");
$result = mysql_query("SELECT * FROM categories")
or die (mysql_error());
?>
<!--SubmitForm-->
<form method="post" action="add_products.php">
<select name="cat">
<?php
while($row = mysql_fetch_array($result))
{echo "<option value='".$row[catid]."'>".$row[catname]."</option>";}
?>
</select><br/>
<input type="text" name="name" value=""><br/>
<input type="submit" value="submit"/>
</form>
add_products.php Code
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
while($row = mysql_fetch_array($result)){
$catn = $row['catid'];
}
$name = mysql_real_escape_string($_POST['name']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
?>
You already seem to have the right values, just need to put them in the correct spot, if you need the 'catid', you can just put it in the id tag of the select.
When you echo the you just need to do this,
echo "<option id='".$row[catid]."' value='".$row[cat]."'>".$row[catname]."</option>";
For more info refer to the w3school manual for , at this link.
Some unrelated, but very important things:
you should escape $cat before it goes into the query
you should always escape strings that go out to HTML with htmlspecialchars
you should always use $row['keyname'], not the deprecated $row[keyname]
Now for your question. The code seems correct on first glance, but I don't have PHP right now so I can't test it. Is there anything in particular that is not working as expected?
You already have it in??
$cat = $_POST['catid'];
If you only want to insert IF they $cat exists, then:
<?php
include("db.php");
$cat = $_POST['catid'];
$query = "SELECT * FROM categories WHERE catname='$cat'";
$result= mysql_query($query) or die ('Mysql Error');
if($result)
{
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
}
?>
You are already assigning the category ID to the category name in the select menu. The variable of the select menu is $_REQUEST['cat'], which holds the ID of the selected category after submitting the form. You can save this value directly to the product table.
However, the while loop in add_products.php is of no use, since you are always assigning the last ID in the table to the variable $catn. Replace this while loop with $catn = $_REQUEST['cat'] (while cat is the name of the select menu).
seem many mistakes here:
select name="cat"
and your try to receive $cat = $_POST['catid']; the correct is $cat = $_POST['cat'];
then you tries to select by catname
$query = "SELECT * FROM categories WHERE catname='$cat'";
when you need to compare ids catid='$cat'";
and what for to assign meny times if the result is single?:
if ( ($row = mysql_fetch_array($result)) ){
$catn = $row['catid'];
}
Your select field is names 'cat', so it should be $_POST['cat'] (or better, rename the select field to 'catid'). And it alreay contains the catid, so there's no need to get it from the DB again (unless you want to make sure it does in fact exist).
Finally, you should escape the $_POST['cat'] parameter as you do the name.
So this is sufficient:
$catid = mysql_real_escape_string($_POST['cat']);
$name = mysql_real_escape_string($_POST['store']);
$query="INSERT INTO products(catid, name) VALUES ('".$catid"','".$name."')";
mysql_query($query) or die ('Error Updating');
echo "Product Added";
Please also look into PDO for the best way to handle DB queries like this.
try change this
"INSERT INTO products(catid, name)VALUES ('".$catn."','".$name."')";
to
"INSERT INTO products(catid, name)VALUES ('".$cat."','".$name."')";

Categories