Change Row in MySQL using PHP Code - php

I'm currently getting the error "Fatal Error: Cannot pass parameter 3 by reference in Update.php on line 14. I need to know how I can fix this.
Here's Update.php:
<?php
$post_json = file_get_contents("php://input");
$post = json_decode($post_json, true);
$response = array();
$configs = include('config.php');
$mysqli = new mysqli($configs["host"], $configs["username"], $configs["password"], "Account"); if($mysqli->connect_errno){
die("Error connecting to MySQL database (".$mysqli->connect_errno.") ".$mysqli->connect_error);
}
$name = $post["Name"];
$rank = $post["Rank"];
$perm = (int) $post["Perm"];
$stmt = $mysqli->prepare("UPDATE accounts SET `rank`=?,`rankPerm`=? WHERE `name`=?");
$stmt->bind_param("sis", $rank, (int) $perm, $name);
$stmt->execute();
?>
I believe that the error is in the (int) part of line 14, but I don't know what's wrong.
I'm trying to edit the "rank" part of one of these rows with this PHP file when executed:
http://imgur.com/a/Ms639
Thanks for all of your help in advance!
NOTE: Already checked update existing row in mysql using php coding

use this
<?php
$post_json = file_get_contents("php://input");
$post = json_decode($post_json, true);
$response = array();
$configs = include('config.php');
$mysqli = new mysqli($configs["host"], $configs["username"], $configs["password"], "Account"); if($mysqli->connect_errno){
die("Error connecting to MySQL database (".$mysqli->connect_errno.") ".$mysqli->connect_error);
}
$name = $post["Name"];
$rank = $post["Rank"];
$perm = (int) $post["Perm"];
$sis="sis";
$stmt = $mysqli->prepare("UPDATE accounts SET `rank`=?,`rankPerm`=? WHERE `name`=?");
$stmt->bind_param($sis, $rank, $perm, $name);
$stmt->execute();
?>
I believe you have to pass variables rather than a string.
Or you could use bindvalue() instead of bindparam() if you're using PDO.

From Php.net
Note:
Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.
It seems when you add a type conversion as a parameter to a function Php doesn't keep the reference, if you remove the (int) in the function call should be fine.
$stmt->bind_param("sis", $rank, (int) $perm, $name);
To
$stmt->bind_param("sis", $rank, $perm, $name);

May be this is the problem...
$name = $_post["Name"];
$rank = $_post["Rank"];
$perm = (int) $_post["Perm"];

Related

PHP MySQL Query Where x = $variable from function

Why is this not working:
function listOrderComments ($factnr){
global $connection;
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
When I echo $factnr I get "123" back.
When I uncommented //$factnr = 123; my function is working.
Looked everywhere for a solution. check the type $factnr is (string).
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.
If you're going to be using that variable I would recommend you use bind_param for your query
Read the PHP manual link below and you will be able to figure out the issue
http://php.net/manual/en/mysqli-stmt.bind-param.php
If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.
public function listOrderComments ($factnr)
{
global $connection;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
$sql->prepare($query);
$sql->bind_param("s", $factnr);
$sql->execute();
$result = $sql->get_result();
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($data as $row) {
print_r($row);
}
}
Then do what you want with the result
You can go with:
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.
Here is an example of the code you would use.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$factnr = "123" // or where-ever you get your input from.
$query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("factnr" => $factnr);
$statement->execute($statementInputs);
//Returns results as an associative array.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
//Shows array of results.
print_r($result);
?>
Use it correctly over "doted" concat. Following will just work fine:
$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
UPDATE:
here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.
function listOrderComments ($factnr){
global $connection;
if (!is_int($factnr)) return -1
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);

how to perform value calculation in mysql database using php

i have a column inside my user table named pairCount which has a value of 2 by default, but whenever an action occur, i want the value to be minus by one (1). so i wrote the following code
<?php
session_start();
require_once './include/Constants.php';
require_once './include/DatabaseConn.php';
require_once './vendor/autoload.php';
require_once './include/User.php';
require_once './include/Level.php';
use \phputil\JSON;
$user = User::getCurrentUser();
$db = new DatabaseConn();
$link = $db->connect();
$sql = "update users set `payee-1` = NULL, status = ?,`pairCount` = ? WHERE `payee-1` = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param('sss', $status, $pairCount, $payee1);
$status = PAIR;
//here is were i did the calculation, but it given me error
$pairCount = $pairCount (-1);
$payee1 = ($user->getUserName());
$res = $stmt->execute();
$stmt->store_result();
if ($res) {
echo "<h1>Congrate you have successfully unsubscribe to a pay this person";
header('Refresh: 3;url=icant3.php');
} else {
echo 'undone';
}
It is also possible to do that in your SQL query.
update users set `payee-1` = NULL, status = ?, `pairCount` = pairCount - 1 WHERE `payee-1` = ?
Then you don't need to do anything with $pairCount variable in your PHP code.

Please check MySQL query

I'm trying to fetch data using MySQLi Query.
Please check my SQL Query, i'm getting error on the If condition.
i add error which is beside
if condition
when it is getting displayed into console
<?php
$id = $_GET['id'];
include("../include/connection_string.php");
$sql = mysqli_query($db, "SELECT pages, main_id FROM dhms_index_table where main_id='"+$id+"'");
if(mysqli_num_rows($sql)){ // Showing error here " Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result"
$data = array();
while($row = mysqli_fetch_array($sql)){
$data[] = array(
'pages' => $row['pages'],
'main_ID' => $row['main_id']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
connections_string.php
$server = 'localhost';
$username ="root";
$passwd ='';
$Dbase = 'og_dhms';
$db = #mysqli_connect($server,$username,$passwd)
or die("Could not connect database");
#mysqli_select_db($db, $Dbase)
or die("Could not select database");
This line
main_id='"+$id+"'
is using + signs rather than dots to concatenate. That is the JS/C method to do that. Maybe you are from that type of background and thought you could use it in PHP; you can't.
so...
main_id='".$id."'
Also make sure you have a value for $id = $_GET['id'];.
Error reporting will tell you if it is or not.
If the GET array is an integer (which I am pretty sure it stands to be), you'd be best to use (int) for it.
$id = (int)$_GET['id'];
and checking if it's set / not empty.
I.e.:
if(isset($_GET['id'])){
$id = (int)$_GET['id'];
}
or
if(!empty($_GET['id'])){
$id = (int)$_GET['id'];
}
Your issue was most likely caused by a query syntax error here:
main_id='"+$id+"'
Changing that to this, should solve the issue:
main_id='".$id."'
But you should not use pure unfiltered user input in your sql statements.
I would do something like this:
<?php
$id = $_GET['id'];
include("../include/connection_string.php");
if($stmt = mysqli_prepare($db, "SELECT pages, main_id FROM dhms_index_table WHERE main_id = ?")) {
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
mysqli_stmt_bind_result($stmt, $pages, $main_id);
$data = array();
while(mysqli_stmt_fetch($stmt)) {
$data[] = array(
'pages' => $pages,
'main_ID' => $main_id
);
}
header('Content-type: application/json');
echo json_encode($data);
}
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
}
?>
Always make sure to use prepared statements when you are including user input on statements to avoid SQL Injection.
Read more about it here: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I hope it helped.

PHP MySQLi bind param for array

I'm having problems with a PHP script that returns some info based on a supplied array of identifiers (MAC addresses).
It gives me a 500 unspecified error.
if (!isset($_POST['macs'])) {
echo 'Please enter mac addresses!';
die;
}
$mysqli = new mysqli("x", "x", "x", "x");
/* check connection */
if ($mysqli->connect_error)
die("$mysqli->connect_errno: $mysqli->connect_error");
$stmt = $mysqli->stmt_init();
/* create a prepared statement */
$query = "SELECT username, mac FROM user WHERE mac IN (" . str_repeat("?,", count($_POST['macs']));
$query = rtrim($query, ",");
$query = $query . ')';
if ($mysqli->prepare($query)) {
call_user_func_array(array($stmt, "bind_param"), array_merge(array('s'), $_POST['macs']));
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['username'];
}
/* close statement */
mysqli_stmt_close($stmt);
}
mysqli_close($link);
This is what I'm posting via the Postman Chrome app:
macs[0] = 'F0:72:8C:F3:B5:66'
macs[1] = 'FA:72:8C:F3:B5:66'
Can anyone at least hint me at what's causing the problem. I'm guessing it's the call_user_func_array call but, I'm unsure of what's the actual problem.
// If you bind array-elements to a prepared statement, the array has to be declared first with the used keys:
Coming to the problem calling mysqli::bind_param() with a dynamic number of arguments via call_user_func_array() with PHP Version 5.3+, there's another workaround besides using an extra function to build the references for the array-elements.
You can use Reflection to call mysqli::bind_param().
Example:
<?php
$db = new mysqli("localhost","root","","tests");
$res = $db->prepare("INSERT INTO test SET foo=?,bar=?");
$refArr = array("si","hello",42);
$ref = new ReflectionClass('mysqli_stmt');
$method = $ref->getMethod("bind_param");
$method->invokeArgs($res,$refArr);
$res->execute();
for more
http://php.net/manual/en/mysqli-stmt.bind-param.php#104073

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';
?>

Categories