Delete command Issue in PHP - php

I have a similar problem with delete command too..
function deleteUsers($userID) {
foreach($userID as $key => $val)
{
$query = "DELETE FROM members WHERE member_id = '$val'";
$result = mysql_query($query);
}
//$query = "DELETE FROM members WHERE member_id = $userID";
//$result = mysql_query($query);
if($result)
{
return 'yes';
}
}
its not performing multi delete.... the $userID contains array. Its not going inside the Query.

When using multiple IDs use variable IN (1,2,3) format rather than simple equality. Also if you have more than one ID maybe the variable should be called $userIDs?
if(count($userID) > 0) {
$query = 'DELETE FROM members WHERE member_id IN ('. implode(',', $userID) .')';
}

Without foreach:
function deleteUsers($userID) {
if (count($userID)) {
$query = "DELETE FROM `members` WHERE `member_id` IN (".implode(",", array_values($userID)).");";
if (mysql_query($query)) { return true; }
}
return false;
}

This will make the function to understand array as well as single integer:
function deleteUsers($u) {
$condition = is_array($u)
? "member_id IN (" . implode(',', $u) . ")"
: "member_id = " . (int)$u;
$res = mysql_query("DELETE FROM `members` WHERE $condition");
return $res ? true : false;
}
Remember that your parameters are not properly escaped and cannot be trusted. To learn more on escaping SQL and preventing injection attacks read about Prepared Statements.

Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Related

Constructing an SQL query around optional search parameters

I'm attempting to construct an MySQL query around some optional search parameters in PHP. There are 3 search fields linking to the three columns in my database. The user should be able to search each column individually, or up to all 3 if they want to narrow down their results.
My PHP code is built so that the if one of the search fields is empty, it doesn't matter and it will continue the search in the other two fields. However, I'm struggling to get my head around how to construct my SQL query afterwards as my where clauses have already been specified in the $whereclauses array. I am returning the same columns in any search the user makes so that should make the SQL query quite simple and mean it only needs to be defined once.
My PHP code:
<?php
require '../db/connect.php';
$whereclauses = array();
$subsets = false;
// for every field
if(!empty($_POST['name']))
{
$subsets = true;
$whereclauses[] = " ARTIST = ". mysql_real_escape_string(trim($_POST['name']));
}
if($subsets)
{
$whereclauses = implode(", ". $whereclauses);
}
else
{
$whereclauses ="";
}
SQL query in PHP
if(!empty($whereclauses)) {
$sql = "SELECT
`ARTIST`, `TRACKTITLE`, `DATE`, `LOCATION`
FROM
`table 3`";
};
$result = mysql_query($sql);
$data = array();
while ($array = mysql_fetch_assoc($result)) {
$data[] = $array;
}
header('Content-type: application/json');
echo json_encode($data);
How can I add the $whereclauses array into my $sql query?
<?php
require '../db/connect.php';
$whereclauses = array("where 1=1");
$subsets = false;
// for every field
if(!empty($_POST['name']))
{
$subsets = true;
$whereclauses[] = " ARTIST = '". mysql_real_escape_string(trim($_POST['name']))."'";
}
Just implode the array in sql
$sql = "SELECT
`ARTIST`, `TRACKTITLE`, `DATE`, `LOCATION`
FROM
`table 3` ".implode(" AND ",$whereclauses);
if(!empty($whereclauses)) {
$sql = "SELECT
`ARTIST`, `TRACKTITLE`, `DATE`, `LOCATION`
FROM
`table 3`";
$sql.= " WHERE 1=1 ";
foreach($whereclauses as $where){
$sql.= " AND ".$where;
}
}
$result = mysql_query($sql);
$data = array();
while ($array = mysql_fetch_assoc($result)) {
$data[] = $array;
}
header('Content-type: application/json');
echo json_encode($data);

mysql query within function with 2argument

well my function is this
function all_products($where, $condition, $where2, $condition2) {
$query = "SELECT *
FROM `product`
WHERE
".mysql_real_escape_string($where)." = '".mysql_real_escape_string($condition)."'
and
".mysql_real_escape_string($where)." = '".mysql_real_escape_string($condition)."'
";
$query_run = mysql_query($query);
return $query_run;
}
so whenever Im trying to use this function to fetch the data from db it returns rows even if only the $where and $condition is true and $where2 and $condition2 is false.
You can support variable length of conditions.
function all_products(array $assoc) {
foreach ($assoc as $key => $value) {
$pairs[] = sprintf(
"`%s` = '%s'",
addcslashes($key, '`'),
mysql_real_escape_string($value)
);
}
$sql = empty($pairs) ?
'SELECT NULL LIMIT 0' :
'SELECT * FROM `product` WHERE ' . implode(' AND ', $pairs);
return mysql_query($sql);
}
However, all mysql_* functions are already DEPRECATED. I strongly recommend you migrate to PDO or mysqli.

the proper fix for SQL Injections? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
i had a sql injection in my code, i checked it with havji.
so i was thinking of a fix, and i set the type of my values to integers or strings
like this. would this do the trick ? like no more injections ??? NOTHING TO WORRY ABOUT ?
my code IS below,
sorry for my bad english!
function get_page_by_id($page_id) {
settype($page_id, "integer");
global $connection;
$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "WHERE id=" . $page_id ." ";
$query .= "LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
// REMEMBER:
// if no rows are returned, fetch_array will return false
if ($page = mysql_fetch_array($result_set)) {
return $page;
} else {
return NULL;
}
}
CODE BEFORE FIX
function get_page_by_id($page_id) {
global $connection;
$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "WHERE id=" . $page_id ." ";
$query .= "LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
// REMEMBER:
// if no rows are returned, fetch_array will return false
if ($page = mysql_fetch_array($result_set)) {
return $page;
} else {
return NULL;
}
}
What you normally want to do is use a prepared statement instead. For php you can read about one option here.
Here is the example from that page
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
Try the following code:
$page_id = mysql_real_escape_string(stripslashes($page_id));

how to combine the function to get the info of certain studid

heres my code
if(isset($_POST['select'])){
$studId = $_REQUEST['studid'];
foreach ($studId as $ch){
echo $ch."<br>";
}
}
//the result of this is like this
c-1111
c-1112
c-1113
// but i want to know their names
i have a function to get the studinfo shown below. how would i apply/insert this in the above code to get the names of those stuid's..pls help
function getuserinfo($ch){
$info_select = "SELECT `$ch` FROM `tbl_student` WHERE `studId`='$ch'";
if ($query_get = mysql_query($info_select)) {
if ($result = mysql_result($query_get, 0, $ch)) {
return $result;
}
}
}
$fname = getuserinfo('fname');
$lname = getuserinfo('lname');
$mname = getuserinfo('mname');
This is wildly dangerous as is, but here is the basic idea:
Your current query inexplicably fetches the student id where student id equals the passed value. So that looks like it is just trying to verify, but it is unnecessary. You want to return all info, then replace the first $ch with just * to fetch all...
function getuserinfo($ch){
$info_select = "SELECT * FROM `tbl_student` WHERE `studId`='$ch'";
if ($query_get = mysql_query($info_select)) {
if ($result = mysql_result($query_get, 0, $ch)) {
return $result;
}
}
}
You call it by passing the id:
getuserinfo($ch);
You can then access all student info for the row. try var_dump(getuserinfo($ch)) to see what's returned if this makes no sense.
But you are just fetching RAW from $_REQUEST with absolutely no cleansing. You are wide open to attack this way.
Switch to PDO or mysqli and use prepared statements. This answer is just to explain how ot get the info. In no way do I condone the use of these deprecated methods as is.
edit
As per your comment, you need to access the result to do something like that...
if(isset($_POST['select'])){
$studId = $_REQUEST['studid'];
$where = "";
foreach ($studId as $ch){
$where .= "studId = '$ch' OR";
}
if(strlen($where) > 0)
{
$where = substr($where, 0, -2);
$result = $mysqli->query("SELECT studId, CONCAT(fname, " ", mname, " ",lname) AS name FROM tbl_student WHERE $where");
while ($row = $result->fetch_assoc()) {
echo $row['name'].'<br>';
}
}
}
...again, sanitize the input. It's not being done in this example. This is just to give an idea

PHP: Making this grabbing from db easier/simpler way?

Is there any method i could do this easier:
$query = mysql_query("SELECT full_name FROM users WHERE id = '$show[uID]'");
$row = mysql_fetch_array($query);
echo $row["full_name"] . " ";
as i only need to grab the full_name, then i make a var for the fetch_array and so, is there any way to make this simpler and echo? There was something about list(), but im not sure..
Ignoring possible security breaches and the usefulness of a DAL (see #deceze's answer), I recommend the use of mysql_result() instead of mysql_fetch_assoc() (or *_array() or whatever):
$query = mysql_query("SELECT full_name FROM users WHERE id = '$show[uID]'");
$fullName = mysql_result($query, 0);
echo $fullName . " ";
Not easier per se but should be more in line with the intention of the query (fetch one field in one row).
The only way to abstract this any more and thereby make the actual call shorter is by using a DAL and/or ORM like Doctrine or Propel, which you should anyway.
May be not easier, but more securely:
$id = mysql_real_escape_string($show['uID']);
$query = mysql_query("SELECT `full_name` FROM `users` WHERE id = '".$id."'");
$row = mysql_fetch_array($query);
echo $row['full_name'];
Oh you can to make id with intval:
$id = intval($id);
This could make further DB-questions easier;
function mysql_fetch_scalar($res)
{
$arr = mysql_fetch_array($res);
return $arr[0];
}
$query = mysql_query("SELECT full_name FROM users WHERE id = '".intval($show[uID])."'");
$fullname = mysql_fetch_scalar($query);
echo $fullname . " ";
Sure.
Moreover, you should - to make a function out of these repetitive API functions calls.
Something as simple, as this
function dbgetvar($query){
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res);
if (!$row) return "";
return $row[0];
}
have this function in your config file and use every time you want a value from database:
echo dbgetval("SELECT full_name FROM users WHERE id = '$show[uID]'");
(I hope you have $show[uID] escaped)
Of course there can be also 2 similar functions, to return a row or a rowset. Or just one but with additional parameter. Or you can combine them into class...
You can make it even escape variables for you:
function dbgetvar(){
$args = func_get_args();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
if (!$query) return false;
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res);
if (!$row) return "";
return $row[0];
}
echo dbgetvar("SELECT full_name FROM users WHERE id = %s",$show['uID']);
That's what you have to do. You could wrap that in a helper function if you're using it a fair bit, but then you'd probably want to cache the answer you get - I don't suppose the name changes all that often...
function echoName($user_id) {
$id = mysql_real_escape_string($user_id);
$query = mysql_query("SELECT full_name FROM users WHERE id = '$id'");
$row = mysql_fetch_array($query);
echo $row["full_name"] . " ";
}
// ...
echoName($show['uID']);

Categories