This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 4 years ago.
I am trying to make the following code to be a php variable. The idea is so I can get all the user data I need by giving the variable the id of the user.
$sql = "SELECT * FROM `users` WHERE user_id='$user_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$displayname = $row['user_displayname'];
}
}
"display name" here is what I want to get.
It works when not in a function but it does not work in the function.
Perhaps I am doing something wrong, here. is how I am doing it.
function get_userdetails($user_id) {
// Figure out displayname of rulechanger
$sql = "SELECT * FROM `users` WHERE user_id='$user_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$displayname = $row['user_displayname'];
}
}
}
Thanks in advance!
Presumably $conn is a global variable (object) representing your database connection. In order to access it inside a function you need to use the global keyword - in this case global $conn;
You will need to do the same with $displayname if you intend to refer to it outside of the function (after the function has set its value). Probably best here will be to simply return $displayname from your function.
Related
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 3 years ago.
I made a simple function that will go into the MYSQL DB and get the field I need based on an id.
It works OUTSIDE the function. Inside the function the SQL statement is correct but I cannot figure out why it will not output the results of $row[$field]. Something I am doing wrong is not displaying when its inside the function.
function getVendor($field,$id) {
$sql = "SELECT $field from manufacturer where id=$id LIMIT 1";
echo $sql;
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row[$field];
}
}
getVendor('name','2');
Your $conn is not in the function scope. Also, You don't need the while loop due the id should be unique.
function getVendor($conn, $field, $id) {
$sql = " SELECT {$field} FROM manufacturer WHERE id={$id} ";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row[$field];
}
getVendor($conn, 'name','2');
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I am trying to write a function that will check for a single value in the db using mysqli without having to place it in an array. What else can I do besides what I am already doing here?
function getval($query){
$mysqli = new mysqli();
$mysqli->connect(HOST, USER, PASS, DB);
$result = $mysqli->query($query);
$value = $mysqli->fetch_array;
$mysqli->close();
return $value;
}
How about
$name = $mysqli->query("SELECT name FROM contacts WHERE id = 5")->fetch_object()->name;
The mysql extension could do this using mysql_result, but mysqli has no equivalent function as of today, afaik. It always returns an array.
If I didn't just create the record, I do it this way:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
Or if I did just create the record and the userID column is AI, I do:
$userID = mysqli_insert_id($link);
Always best to create the connection once at the beginning and close at the end. Here's how I would implement your function.
$mysqli = new mysqli();
$mysqli->connect(HOSTNAME, USERNAME, PASSWORD, DATABASE);
$value_1 = get_value($mysqli,"SELECT ID FROM Table1 LIMIT 1");
$value_2 = get_value($mysqli,"SELECT ID FROM Table2 LIMIT 1");
$mysqli->close();
function get_value($mysqli, $sql) {
$result = $mysqli->query($sql);
$value = $result->fetch_array(MYSQLI_NUM);
return is_array($value) ? $value[0] : "";
}
Here's what I ended up with:
function get_col($sql){
global $db;
if(strpos(strtoupper($sql), 'LIMIT') === false) {
$sql .= " LIMIT 1";
}
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query);
return $row[0];
}
This way, if you forget to include LIMIT 1 in your query (we've all done it), the function will append it.
Example usage:
$first_name = get_col("SELECT `first_name` FROM `people` WHERE `id`='123'");
Even this is an old topic, I don't see here pretty simple way I used to use for such assignment:
list($value) = $mysqli->fetch_array;
you can assign directly more variables, not just one and so you can avoid using arrays completely. See the php function list() for details.
This doesn't completely avoid the array but dispenses with it in one line.
function getval($query) {
$mysqli = new mysqli();
$mysqli->connect(HOST, USER, PASS, DB);
return $mysqli->query($query)->fetch_row()[0];
}
First and foremost,
Such a function should support prepared statements
Otherwise it will be horribly insecure.
Also, such a function should never connect on its own, but accept an existing connection variable as a parameter.
Given all the above, only acceptable way to call such a function would be be like
$name = getVal($mysqli, $query, [$param1, $param2]);
allowing $query to contain only placeholders, while the actual data has to be added separately. Any other variant, including all other answers posted here, should never be used.
function getVal($mysqli, $sql, $values = array())
{
$stm = $mysqli->prepare($sql);
if ($values)
{
$types = str_repeat("s", count($values));
$stm->bind_param($types, ...$values);
}
$stm->execute();
$stm->bind_result($ret);
$stm->fetch();
return $ret;
}
Which is used like this
$name = getVal("SELECT name FROM users WHERE id = ?", [$id]);
and it's the only proper and safe way to call such a function, while all other variants lack security and, often, readability.
Try something like this:
$last = $mysqli->query("SELECT max(id) as last FROM table")->fetch_object()->last;
Cheers
i am a newbie at php oop.So I have a problem.
I have a user class, I want to control if there is a member with this ID or nickname.But the page that i want the control if user exists, I cant reach the $query.
this is my Staff class php file
public static function info($id = null, $nick = null){
if($id){
$query = mysql_query("SELECT * FROM staff WHERE yetkili_id = '$id' ");
}elseif($nick) {
$query = mysql_query("SELECT * FROM staff WHERE yetkili_nick = '$nick'");
}
if(mysql_num_rows($query) > 0){
return $query;
}
}
and this is the page that i want to take info of user
<?php
Staff::info(1);
$row = mysql_fetch_array($query);
print_r($row);
?>
and I get this error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\oneriyor\admin\login.php on line 3
I dont know what is the solution.If you can help me guys i will be appreciate.
As #frederico says, you have a variable scope misunderstanding.
Your $query is inside your function. So you can use it only inside. Try to move your "fetch" inside your function instead of your return. And follow the #frederico's link !
This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\xxx\dash.php on line 20
I am quite fairly new, and being a old-school coder, simply using mysql_result to grab such data, I am unaware of how to go about this. I have a class->function setup.
Line 20 of dash.php contains:
echo $user->GetVar('rank', 'Liam', $mysqli);
While, the function is:
function GetVar($var, $username, $mysqli)
{
$result = $mysqli->query("SELECT " . $var . " FROM users WHERE username = '" . $username . "' LIMIT 1");
return $result;
$result->close();
}
Now, to my understanding, I am meant to convert $result into a string, but I am not fully aware of how to do so. I've tried using a few methods, but to no avail. So I've come to the community to hopefully get a answer, I've also looked around but noticed that all other threads are asking for num_rows, while I just want to grab the string from the query select.
You have to fetch it first before echoing the results. Rough Example:
function GetVar($var, $username, $mysqli) {
// make the query
$query = $mysqli->query("SELECT ".$var." FROM users WHERE username = '".$username."' LIMIT 1");
$result = $query->fetch_assoc(); // fetch it first
return $result[$var];
}
Then use your function:
echo $user->GetVar('rank', 'Liam', $mysqli);
Important Note: Since you're starting out, kindly check about prepared statements. Don't directly append user input on your query.
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_object()) {
echo row['column_name'];
}
}
$result->close();
where you see 'column_name put the name of the column you want to get the string from.
This question already has answers here:
How do you debug PHP scripts? [closed]
(30 answers)
Closed 9 years ago.
i know this must be only a small bug, but i cant find it.
My function:
function del_mysql($table,$id)
{
$id = $_GET['id'];
$exec = mysqli_query($con, "delete from $table where id = '$id'");
return $exec;
}
in Code:
if ($_GET['action'] == 'delete')
{
del_mysql("awsome","$id");
}
if make in function:
$id = $_GET['id'];
echo $table;
echo $id;
i get right table and id.
Somebody see the bug?
I removed already the $exec and return part and leave only mysqli_query command. but dont want to work.
The problem is that in your del_mysql function, you are referencing the connection object $con, which does not exist in the scope of the function. Either pass it into the function as a parameter like this:
function del_mysql($table, $id, $con) {
or access it as a global variable like this:
function del_mysql($table, $id) {
global $con;
I hope that helps.
Regards,
Ralfe