mysql to mysqli function difficulties - php

I am converting this function:
function user_data($user_id) {
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`' . implode('`, `', $func_get_args) . '`';
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE `user_id` = $user_id"));
return $data;
}
}
From mysql to mysqli however I am encountering difficulties wrapping my head around this and understanding why I'm not even getting any errors, here is my attempt at a mysqli version:
function user_data($user_id) {
global $link;
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`' . implode('`, `', $func_get_args) . '`';
$result = $link->query("SELECT $fields FROM `users` WHERE `user_id` = $user_id");
if(!$result){
printf("Errormessage: %s\n", $link->error);
}else{
while($data = $result->fetch_assoc()){
print_r($data);
}
}
}
}
Any guidance or tips is much appreciated.

if ($func_num_args > 1) {
This line is preventing any of the enclosed code from being executed when you only pass one argument into the user_data() function. This function was designed to be passed a user id AND a list of columns to select data from in the users database table.
Instead of calling user_data(25);
try something like
user_data(25, 'column_name1', 'column_name2');

Related

Object of class mysqli could not be converted to string

I had my old website so I've decided to change it from mysql_ to mysqli so I've managed to complete 40% and now i am stuck with this problem.Help Me!
I am getting error on 'implode()' function
function user_data($user_id,$conn){
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1){
unset($func_get_args[0]);
$fields = '`'.implode('`,`',$func_get_args).'`';
$query = "SELECT ".$fields." FROM users WHERE user_id = ".$user_id."";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
while ($row = $result->fetch_assoc()) {
$data = $row['user_id'];
}
return $data;
}
}
In order to get below code to work properly
if (logged_in() === true){
$session_user_id = $_SESSION['user_id'];
$user_data = user_data($session_user_id,'user_id','username',
'password','first_name','last_name','email','type',$conn);
}
Any alternate way to perform same task will
You have not correct definition of user_data function,
In it's signature you have only two arguments:
function user_data($user_id, $conn)
So, these arguments are $user_id and $conn.
But when you call your user_data you pass more than 2 arguments:
user_data($session_user_id,'user_id','username', 'password','first_name','last_name','email','type',$conn);
See, you have 8 arguments here. And $conn is not the second one, it's eighth!
And when you do
$fields = '`'.implode('`,`',$func_get_args).'`';
last argument which holds your mysqli-connection is being added to $fields.
So, you have to rewrite your function, for example this way:
function user_data($user_id, $conn, $fields) {
$data = array();
$user_id = (int)$user_id;
$fields = '`'.implode('`,`', $fields).'`';
$query = "SELECT ".$fields." FROM users WHERE user_id = ".$user_id."";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
while ($row = $result->fetch_assoc()) {
$data = $row['user_id'];
}
return $data;
}
And call it for example:
$user_data = user_data(
$session_user_id, // $user_id
$conn, // $conn
array('user_id','username','password','first_name','last_name','email','type') // fields as ARRAY
);
$func_get_args has $user_id, other string values and at last the mysqli connection object. You must unset last element of function parameters. Correct user_data function is that:
function user_data($user_id,$conn){
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1){
unset($func_get_args[0]);
unset($func_get_args[ $func_num_args - 1]); // you must delete last element becouse this is mysqli object
$fields = '`'.implode('`,`',$func_get_args).'`';
$query = "SELECT ".$fields." FROM users WHERE user_id = ".$user_id."";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
while ($row = $result->fetch_assoc()) {
$data = $row['user_id'];
}
return $data;
}
}

PHP MySQLi function get user data can't work

i am using This code for showing user data record but this code is not work on my side
I want to echo out specific user data. I created a function where I insert multiple arguments (each argument represents a column in the database) and then echo whichever column I want with a simple line of code.
Index.php
include('function.php');
$conn = new MySQLi(localhost, root, password, database);
$user_id = $_SESSION['login_user']; // like 1
$user = user_data($conn, $user_id, 'login', 'pass', 'nikename', 'email');
if(empty($user)){
echo 'error'; // always showing this error
}else{
echo $user['nickename'];
}
Always Showing echo 'error';
function user_data($conn, $user_id){
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
unset($func_get_args[1]);
$valid = array('login', 'pass', 'nikename', 'email');
$fields = array();
foreach($func_get_args as $arg) {
if(in_array($arg, $valid)) $fields[] = $arg;
}
$fields = '`' . implode ('`, `', $fields) . '`';
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('si', $fields, $user_id);
$stmt->execute();
//here I am trying to convert the result into an array
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
return $results;
$stmt->close();
}
}
}
Seeing and analyzing your code several times, I think the below will solve your issue.
Add this before your while/fetch loop
$row = array();
stmt_bind_assoc($stmt, $row);
so your code will look like this
$row = array();
stmt_bind_assoc($stmt, $row);
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
Also make sure you read the full documentation of bind_param on php.net here
Thanks and Best Regards
I guess, instead of
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('si', $fields, $user_id);
you should go with
if($stmt = $conn->prepare("SELECT $fields FROM `users` WHERE `user_id` = ?")) {
$stmt->bind_param('i', $fields, $user_id);
Bind parameters. Types: s = string, i = integer, d = double, b = blob
As far as you have one argument with type INT you need to pass 'i' as a first parameters.
Try debugging over line by line in that function where you will get exact flaw by var_dump().

How use an array/implode in the SELECT query PDO

i have a function that returns user data from the database. But I want to return only the selected row, for instance username, so i created an array for that, giving the option to echo $userdata['anything']. see the code:
$session_user_id = $_SESSION['user_id'];
$user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name'); }
and
function user_data($user_id){
$pdo = new PDO("mysql:host=localhost;dbname=MYDATABASE;", "MYUSERNAME", "MYPASSWORD");
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`' . implode(', ', $func_get_args) . '`';
echo $fields;
$stmt = $pdo->prepare("SELECT :fields FROM `users` WHERE `user_id` = :user_id");
$stmt->execute(array(':user_id' => $user_id, ':fields' => $fields));
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($data);
}
}
The problem is that this doesn't work. It returns
Array ( [0] => Array ( [`user_id, username, password, first_name, last_name`] => `user_id, username, password, first_name, last_name` ) )
However, replacing :fields with for instance 'username' does work. Is it possible to use this implode?
Change:
$stmt = $pdo->prepare("SELECT :fields FROM `users` WHERE `user_id` = :user_id");
to:
$stmt = $pdo->prepare("SELECT $fields FROM `users` WHERE `user_id` = :user_id");
and remove $fields from the execute parameter array.
Parameterized placeholders are only for values.
UPDATE
Also this line is wrong:
$fields = '`' . implode(', ', $func_get_args) . '`';
This will output a ` outside the the field list rather than each column name.
Try removing them like this:
$fields = implode(', ', $func_get_args);

Variable between php files

Before anyone points out my code is flawed in security or etc know that I am quite a PHP noob and wouldn't mind you forwarding some help to fix that rather than just yelling it is terrible.
Also I did try this below and it won't work for me because it stores it into the session (Unless session is more secure than I thought. I assume users can extract data from one, correct?):
http://tinyurl.com/myqx3xo
As for my question, how would I be able to access the variable $connectdb in my users function? When I do that it gives me 'Undefined variable' error, and isn't detecting that it exists whatsoever. Both are requires in main\folder\start.php that is loaded every page, and on those pages I attempted to call the function and it gave me a failure. The code works fine when I attempt to hardcode the $connectdb's varible into the functions but again there are good reasons not to. Will add additional details if required.
Undefined variable: connectdb in main\folder\folder1\users.php on the line that starts with $data
main\folder\folder1\users.php function:
function user_data($id) {
$data = array();
$user_id = (int)$id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '' . implode(', ', $func_get_args) . '';
$data = mysqli_fetch_assoc(mysqli_query($connectdb,"SELECT $fields FROM users WHERE id = $id"));
return $data;
}
}
main\folder\folder2\connect.php:
<?php
$connect_fail = 'Example connection failure.';
$dbhost = 'host';
$dbuser = 'user';
$dbpass = 'pass';
$db = 'database';
$connectdb = mysqli_connect($dbhost, $dbuser, $dbpass, $db) or die($connect_fail);
?>
include your connect.php into your user.php
include('../fodler2/connect.php');
function user_data($id) {
$data = array();
$user_id = (int)$id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '' . implode(', ', $func_get_args) . '';
$data = mysqli_fetch_assoc(mysqli_query($connectdb,"SELECT $fields FROM users WHERE id = $id"));
return $data;
}
}
in your users.php file you need to add
include "../folder2/connect.php";

PHP function to fetch data as arrays and display

I came up with this piece of code from others work to gather data from database and display it the simplest and safest way without loop. However it doesn't really work and I would like to know why?
So my main question is how to make it work?
And the 2:nth how to make it as secure as possible?
Code to display data:
<?php echo $webdata['web_name']; ?>
Code in init.php:
$webdata = webdata('id', 'web_name');
Code for function:
function webdata($data) {
$web_data = array();
$func_num_args = func_num_args();
$func_get_args = func_get_args();
global $db_connect;
if ($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`' . implode('`, `', $func_get_args) . '`';
$query = "SELECT $fields FROM `settings` WHERE id = 1";
$result = $db_connect->query($query);
while ($web_data = $result->fetch_assoc()) {
return ($web_data);
}
}
}
You don't have a data variable from the query. You have a webdata variable however...
Instead:
while ($webdata = $result->fetch_assoc()) { return ($data); }
Use:
while ($webdata = $result->fetch_assoc()) { return ($webdata); }
You just return the first row, is this what you want?
You don't use the $data variable, what should it be for?
This is as secure as it gets: you don't have any means inject something into the query...

Categories