how to store posted parameter in array using slimframework 3 - php

i want to store the posted parameters to my function in an array,
i am using slim 3
My question
is the request->getparam('') how i should get the parameters
posted ?
should i bind them ? if so to what should i bind them since i am
not using :Adminusera :Adminuserb :Adminuserc anywhere
is there a way i could place for example this in my array value :Adminusera instead of $userA ?
my code:
//IS THIS HOW I GET THE POSTED PARAMETERS To My Function ?
$userA = $request->getParam('usera');
$userB = $request->getParam('userb');
$userC = $request->getParam('userc');
$sql = "SELECT *FROM admins";
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':Adminusera', $userA);
$stmt->bindParam(':Adminuserb', $userB);
$stmt->bindParam(':Adminuserc', $userC);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_OBJ);
$db = null;
if(!empty($admin)){
$newUsers = array('a' => $userA, 'b' => $userB, 'c' => $userC);
print_r($newUsers);
}
}

Turns out i don't need to use bindparam i could just do it like this
$userA = $request->getParam('usera');
$userB = $request->getParam('userb');
$userC = $request->getParam('userc');
$sql = "SELECT *FROM admins";
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_OBJ);
$db = null;
if(!empty($admin)){
$newUsers = array('a' => $userA, 'b' => $userB, 'c' => $userC);
print_r($newUsers);
}
}
thus i need to send the post request to my function using x-www-form-urlencoded

Related

code to search for a constant value by posting the column name is not working need some correction

I am trying to retrieve user data from a database ... value is constant ("t") and i have so many columns to search in so i have decided to post the column name using post method and look for the constant value("t" in my case). I have created this code but it's not working, please check the code and i am testing it using postman so attaching a screenshot please take a look for what error i am getting.
My function in DbOperations.php
<?php
class DbOperations{
private $con;
function __construct(){
require_once dirname(__FILE__).'/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
//CRUD -> c -> CREATE
//Test Purpose
public function gettestuser($value, $pin){
$valid_columns = array('a' => 1, 'b' => 1, 'ho' => 1, 'll' => 1, 'c' => 1, 'd' => 1);
if (!array_key_exists($value, $valid_columns)) {
throw new Exception("Error Processing Request", 1);
}
$stmt = $this->con->prepare("SELECT * FROM test_category WHERE $value = 't' pin = ?");
$stmt->bind_param("ss", $value, $pin);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
}
?>
My gettestuser.php
<?php
require_once '../include/DbOperations.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(isset($_POST['reg_value']) && isset($_POST['reg_pin'])){
$db = new DbOperations();
$test_category = $db->gettestuser($_POST['reg_value'], $_POST['reg_pin']);
var_dump($test_category);
$response['error'] = false;
$response['pid'] = $test_category['pid'];
$response['name'] = $test_category['name'];
$response['pin'] = $test_category['pin'];
$response['a'] = $test_category['a'];
$response['b'] = $test_category['b'];
$response['ho'] = $test_category['ho'];
$response['ll'] = $test_category['ll'];
$response['c'] = $test_category['c'];
$response['d'] = $test_category['d'];
}else{
$response['error'] = true;
$response['message'] = "Required fields are missing";
}
}
echo json_encode($response);
?>
My Table Structure
For adding dynamic field you have to bind params for field names. Also you forgot and for combine conditions so change your code to :
$stmt = $this->con->prepare("SELECT * FROM test_category WHERE $value = 't' and pin = ?");
$stmt->bind_param("s", $pin);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();

DELETE multiple rows in PDO

I'm a rookie in PDO and I've done some search about the issue I'm facing and I wasn't able to find any answers about it. As you can see below, I have this function:
function deleteInfo($id){
$pdo = connPDO();
$deleteInfo = $pdo -> prepare("DELETE FROM game_locais_zumbis WHERE id_zumbi IN (:id)");
$deleteInfo -> bindValue(":id", $id, PDO::PARAM_STR);
$deleteInfo -> execute();
$pdo = null;
}
After that, I have the following code:
while($row = $listInfo -> fetch(PDO::FETCH_ASSOC)){
$ids[] = $row['ids'];
}
$ids = implode(',', $ids);
deleteInfo($ids);
When I echo my $ids, I get:
1,2,3,4,5
But the DELETE function is not deleting all those five rows in my db but only the first one, like "1". When I run that exactly same DELETE function in my db, replacing the ":id" with "1,2,3,4,5", it does work! Does anybody know what's my mistake here? I appreciate any help.
I would do this:
$query = "DELETE FROM game_locais_zumbis WHERE id_zumbi in (".str_repeat("?,", count($ids) - 1)."?)";
$stmt = $conn->prepare($query);
$stmt->execute($ids);
Unfortunately you can't bind an array of elements with prepared statements. You will have to build them in the query directly.
function deleteInfo($ids)
{
$pdo = connPDO();
if (!is_array($ids))
$ids = array($ids); // if it is just one id not in an array, put it in an array so the rest of the code work for all cases
$ids = array_map([$pdo, 'quote'], $ids); // filter elements for SQL injection
$pdo->exec('DELETE FROM game_locais_zumbis WHERE id_zumbi IN (' . implode(', ', $ids) . ')');
}
Remember to pass the array to deleteInfo() instead of imploding it into a string.
This is how i have done it and it worked. I created an array and looped through it.
<?php
// set a database connection
$host = "localhost";
$user ="root";
$password = "";
$db = "pdopost";
//Set a DSN
$dsn = 'mysql:host ='.$host . ';dbname='.$db;
// Create a PDO instance
$pdo = new PDO ($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$ids=['6', '7'];
foreach($ids as $id){
$sql = "DELETE FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
}
echo 'Deleted in the database';
?>

returning multiple rows from mysql in php

I'm trying to write a PHP-script that will fetch multiple rows from MySQL and return them as a JSONObject, the code works if I try to only fetch 1 row but if I try to get more than one at a time the return string is empty.
$i = mysql_query("select * from database where id = '$v1'", $con);
$temp = 2;
while($row = mysql_fetch_assoc($i)) {
$r[$temp] = $row;
//$temp = $temp +1;
}
If I write the code like this it returns what I expect it to, but if I remove the // from the second row in the while loop it will return nothing. Can anyone explain why this is and what I should do to solve it?
You are using an obsolete mysql_* library.
You are SQL injection prone.
Your code is silly and makes no sense.
If you really wan to stick to it, why simply not do:
while($row = mysql_fetch_assoc($i)) {
$r[] = $row;
}
echo json_encode($r);
And finally, an example using PDO:
$database = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_pass';
$pdo = new \PDO('mysql:host=localhost;dbname='. $database, $user, $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try
{
$stmt = $pdo->prepare("SELECT * FROM your_table WHERE id = :id");
$stmt->bindValue(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
catch(\PDOException $e)
{
$results = ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine());
}
echo json_encode($results);
You don't need the $temp variable. You can add an element to an array with:
$r[] = $row;

Simple PDO update is not working

The problem is on :soundid if I type manually soundid='soundidfromPOST' received from POST, the row is updated, but with soundid=:soundid ... nothing. Why?
PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION and error_reporting enabled.
public function save($args) {
$userid = Controller::getUserConnection();
if ($userid) {
$soundid = $_POST['soundid'];
$track_title = $_POST['track_title'];
$track_artist = $_POST['track_artist'];
$track_album = $_POST['track_album'];
$track_genre = $_POST['track_genre'];
$track_description = $_POST['track_description'];
$played = 1;
$statement = $this->_db->prepare("UPDATE sounds SET title=:track_title, artist=:track_artist, album=:track_album, genre_id=:track_genre, description=:track_description, played=:played WHERE soundid=:soundid AND userid=:userid AND ip=:ip");
$statement->bindParam(':soundid',$soundid,PDO::PARAM_STR);
$statement->bindParam(':userid',$userid,PDO::PARAM_INT);
$statement->bindParam(':track_title',$track_title,PDO::PARAM_STR);
$statement->bindParam(':track_artist',$track_artist,PDO::PARAM_STR);
$statement->bindParam(':track_album',$track_album,PDO::PARAM_STR);
$statement->bindParam(':track_genre',$track_genre,PDO::PARAM_INT);
$statement->bindParam(':track_description',$track_description,PDO::PARAM_STR);
$statement->bindParam(':ip',$_SERVER['REMOTE_ADDR'],PDO::PARAM_STR);
$statement->bindParam(':played',$played,PDO::PARAM_INT);
$statement->execute();
echo 'saved!';
}
}
I would do the following to make it cleaner and because you don't need to bind everything explicitly (please note I didn't use all your variables):
Assign all your post data that you want to use in the query to an array:
$data = array(
'userid' => $userid,
'sounddid' => $_POST['soundid'],
'track_title' => $_POST['track_title'],
'track_artist' => $_POST['track_title'],
'ip' => $_SERVER['REMOTE_ADDR'],
);
Write you query:
$sth = $this->_db->prepare("
UPDATE sounds SET
title = :track_title,
artist = :track_artist
WHERE soundid = :soundid
AND userid = :userid
AND ip = :ip
");
Pass in your data array to be executed:
$result = $sth->execute($data);

Mysqli prepared statement num_rows with multiple parameters

I have the following script:
<?php
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$statement = $mysqli->stmt_init();
$query = 'SELECT * FROM table WHERE id = ? AND active = 1';
$statement->prepare($query);
$parameters = array('i');
$inputParameters = array(10);
foreach ($inputParameters as $param) {
$parameters[] =& $param;
}
call_user_func_array(array($statement, 'bind_param'), $parameters);
$statement->execute();
$statement->store_result();
echo $statement->num_rows;
?>
Which returns exactly the right number of rows.
But when I change the script to:
<?php
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$statement = $mysqli->stmt_init();
$query = 'SELECT * FROM table WHERE id = ? AND active = ?';
$statement->prepare($query);
$parameters = array('ii');
$inputParameters = array(10, 1);
foreach ($inputParameters as $param) {
$parameters[] =& $param;
}
call_user_func_array(array($statement, 'bind_param'), $parameters);
$statement->execute();
$statement->store_result();
echo $statement->num_rows;
?>
It returns 0. Does anyone have an explanation for that? To me it looks like num_rows stops working as soon as you have more than 1 param bound to the statement.
p.s: in the full script there's a reason to use call_user_func_array here, not using call_user_func_array gives the same result.
I found the answer after a lot of debugging: $parameters will be array('ii', 1, 1) in the second code. This is because of the reference used there. Changing foreach ($inputParameters as $param) { to foreach ($inputParameters as &$param) { fixed the problem

Categories