I've been trying to write a function to draw a usernames name from the database fetch he result then return it back to the parent page but nothing I have tried works and I don't even know where to go from here. my old code that I used mysql on works perfect and was easy to put together but this mysqli and all its double parameters and stuff I cant figure it out. so basically I am asking for anyone who knows how to set one of these up.
(SELECT name FROM users WHERE username = '" .$_SESSION['username']. "')
I want to mysqli_real_escape the value if possible so if anyone knows how to set up a function to return a value back to its parent page I would much appreciate it.
It's very similar to using mysql_* functions:
function get_user_name()
{
global $conn;
$sql = "SELECT name FROM users WHERE username = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("s", $_SESSION['username']);
$stmt->execute();
$result = $stmt->get_result();
$data = mysqli_fetch_assoc($result);
return $data['name'];
}
}
Related
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
Would someone please me with the code below, I am inexperienced in this area and my class in SQL was "A long time ago in a galaxy far, far away..." I know the connection string works because I have used it in other functions with this app. I have even used the code below for retrieving *rows from another table in another function, for the most part, except that I didn't use the WHERE clause.
First, I am able to store IP addresses in the table using a function and it is working well. Now I want to check to see if a given one exist in this table. Partial code is given below.
What seems to always return is 0 rows. I have put in test data into the table and hard-coded the $ipA, but I still get 0 rows return. Please help if possible and thanks for the effort spent.
function checkDB($ipA) {
require_once('connection.inc.php');
$resultAns = "";
//create db connection
$conn = dbConnect();
//init prepared stmt
$stmt = $conn->stmt_init();
//Set sql query for ipAddress search
//prepare the SQL query
$sql = 'SELECT * FROM ipAddress WHERE ipA = ?';
//submit the query and capture the result
if ($stmt->prepare($sql)) {
$stmt->bind_param('s', $ipA);
$stmt = $stmt->execute();
//if qry triggers error affeted_rows value becomes -1 &
//php treats -1 as true; so test for greater than 0
$numRows = $stmt->num_rows; //not to sure about the syntax here
}
// I want to know if the query brought back something or not, I don't what
// to know exactly what, only that it found a match or did not find a match.
// echos are for testing purposes to show me where I am landing.
if ($numRows == 0) {
echo '<script type="text/javascript">window.alert("numRows = 0")</script>';
$resultAns = 0;
} elseif ($numRows == 1) {
echo '<script type="text/javascript">window.alert("numRows = 1")</script>';
$resultAns = 1;
}
return $resultAns;
}
Try storing the result after you execute
$stmt->store_result();
Use $stmt->store_result(); before you call num_rows.
While the others caught one reason that $numRows would never receive a value other than 0, the other piece of code that was flawed and caused problems was...
$stmt = $stmt->execute(); which should have been just $stmt->execute();
I must have mixed it up with other code I wrote from somewhere else.
Thanks for the answers, they did help.
I'mm currently going through the process of changing my code and have hit a bit of a wall so thought id ask and see if anyone can help me with the new code...
firstly i have quite a few mysql_result() dotted around my code and would like to know how to write the code for the new process.. here is an example of one of my functions that has code that needs changing, I've done some its the mysql_result() part that I need to know how to rewrite..
function user_exists($db,$username) {
$username = sanitize($db,$username);
$sql = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
return(mysql_result($sql, 0) == 1) ? true : false;
}
Also while I'm here I may as well ask.. I also have this function to, well sanitize code but i keep reading that mysql_real_escape_string is not so safe. I've read that i should be using prepared statements, I'm just not to sure how to implement it into my code..here is the sanitize function that is basically just mysql_real_escape_string()..
function sanitize($db, $data) {
return mysqli_real_escape_string($db, $data);
}
so how would i make this correct? cause from what im reading its just putting prepare before a query like..
$sql = $db->prepare("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username'");
so my question is, can anyone help me change these codes to correct up-to date versions?
What you want to use is the PDO Class and bind values (http://www.php.net/manual/en/class.pdo.php).
So something like the following should work:
$stmt = $db->prepare("SELECT 1 FROM users WHERE username = ?");
$stmt->execute([$username]);
return $stmt->fetchColumn();
im trying to use mysqli with bind_result but all i get is null values. My $stmt
number of rows is greater than 0 so i do have some data in it.
I dont realy understand what value should come into bind_result
I have read at the manual http://php.net/manual/en/mysqli-stmt.bind-result.php
And they dont explain what should i put in the bind_result.
Should i put there the column names? if yes, as strings? how do i get my wanted values?
Here is my code thanks for helping:
$sql = "SELECT * FROM comments WHERE workout_name = ? AND user = ?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error."[$sql]");
$stmt->bind_param('ss', $workout_name, $user);
$workout_name = "rytg";
$user = "tomer";
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($comment, $commented_user);
if($stmt->num_rows > 0)
{
$response["workouts"] = array();
while ($stmt->fetch())
{
// temp user array
$workouts = array();
$workouts["comment"] = $comment;
$workouts["user"] = $commented_user;
// push single product into final response array
array_push($response["workouts"], $workouts);
}
}
Your only problem is insufficient error reporting
error_reporting(E_ALL);
ini_set('display_errors',1);
Just add these lines at the top of your code and you will be immediately informed of the exact problem with your code.
Note that on the production server you have to turn displaying errors off and logging on
I don't have a working PHP installation next to me at the moment, so I can't verify it, but I believe you might have to bind both parameters and result before you execute the query, like so:
$workout_name = "rytg";
$user = "tomer";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error."[$sql]");
$stmt->bind_param('ss', $workout_name, $user);
$stmt->bind_result($comment, $commented_user);
$stmt->execute();
I'm not too sure about store_result() either. I don't recall having to use it while retrieving the results, so you might want to try running your code without it and see what happens.
I'm currently trying to create a function where I can control what field and what values get pulled. This is something I had in mind, but it doesn't work. I get no error, it returns an empty array.
public function test ($field, $id) {
$sql = $this->con->prepare("SELECT ? FROM Content WHERE id=?");
$sql->bindParam(1, $field);
$sql->bindParam(2, $id);
$sql->execute();
while ($row = $sql->fetch()) {
echo $row;
}
}
I'm unsure about the "SELECT ?..." part I'm not 100% sure that is the correct way. The basic idea is I can make a call anywhere like:
< ?php $obj = new handler; $obj->test($_GET['Title'], $_GET['id']); ?> which will echo the Title with the correct id.
the way prepared statements work is that the quesry is prepared and then the data for the fields is sent. Because the first '?' refers to an actual part of query it can not be prepared.
Workarounds:
a) Fetch the whole row and return just the field you need
$this->con->prepare("SELECT * FROM Content WHERE id=?");
//.......
return $row->$field;
b) Insert the field raw into the query (you can use quotes though)
$this->con->prepare("SELECT `{$field}` FROM Content WHERE id=?");
Also if you intend to use it like the way you described it is possible that you be making a whole lot of dduplicate calls to the database