Basically what I want to do is to use MySqli to just do a query UUID_SHORT() and get the result. No INSERT,UPDATE,DELETE or anything, I just want the value of UUID_SHORT.
Haven't been able to figure it out, any help would be great!
Thanks.
How about SELECT UUID_SHORT();
There is more information in the MySQL documentation.
Example:
function UUID_SHORT(mysqli $db)
{
$result = $db->query("SELECT UUID_SHORT();");
$res = $result->fetch_array();
return $res[0];
}
You can expand function created by #competent_tech to add more flexibility:
Example:
function getUuid(mysqli $db, $short=false)
{
$query = "SELECT " . ($short ? "UUID_SHORT()" : "UUID()");
$result = $db->query($query)->fetch_array();
return $result[0];
}
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
I'm having some difficulty returning an array out of a while lopp which I have in a function. Here is the code I am using. I am meant to be able to return an array of results from the function which contains the id numbers of pictures associated with a particular user id - in this case I want to print_r the array for the user id of 17. When this code isn't in the function it works, but when I place it in the function, no luck. I presume its related to a mistake I am making in the returning of the array. Your help is greatly appreciated.
function picture($id)
{
$sql = "SELECT * FROM avatar WHERE user_id={$id}";
$result = $database->query($sql);
$results = array();
while ($row = mysql_fetch_assoc($result))
{
$results[] = $row;
}
return $results;
}
$results = picture(17);
print_r($results);
Your function can't access your MySQL link identifier
First of all, you're mixing object-oriented paradigm ($database->query($sql)) with procedural paradigm (mysql_fetch_assoc($result)) which will make your code a nightmare to maintain.
Assuming that $database is a mysql_ link identifier, you'll need to pass it into your function in order to access it there.
function getUserAvatar($database, $id){
$sql = 'SELECT * FROM `avatar` WHERE `user_id`=' . intval($id) . ' LIMIT 1;';
$result = mysql_query($database, $sql);
$row = mysql_fetch_assoc($result);
return $row;
}
$results = picture($database, 17);
Don't just copy-paste that, keep reading!
The above will probably work, but if you're allowing a user to pass that user ID into the function, it's quite possible that they'll be able to find a vulnerability to inject an SQL statement of their choice into your MySQL database.
mysql_ functions are deprecated, so you should ideally stop using them and switch to mysqli or PDO. You'll also want to get an understanding of prepared statements in order to prevent SQL injections. If you can't upgrade, look at the mysql_real_escape_string and intval functions and make sure you sanitize all user inputs before processing them.
The resulting code will look something like this, if you switch to mysqli and prepared statements:
function getUserAvatar($db, $userId) {
$stmt = $db->prepare("SELECT * FROM `avatar` WHERE `user_id`=? LIMIT 1;");
$stmt->bind_param("i", $userId);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_assoc();
}
$db = new mysqli("localhost", "user", "password", "database");
$result = getUserAvatar($db, 17);
may be you should try this..
function picture($id)
{
$sql = "SELECT * FROM avatar WHERE user_id={$id}";
$result = $database->query($sql);
$row = mysql_fetch_assoc($result);
return $row;
}
$results = picture(17);
print_r($results);
I am not familiar in this style of coding syntax but I want to use this for my project.
I have a question on how to integrate this query:
SELECT max(id) FROM assignment_billing WHERE assignment_id = 37
into this syntax.
public function fetchBillingByParentId($db,$id) {
$select = $db->select()->from('assignment_billing')->where('assignment_id = '.$id);
$stmt = $select->query();
$result = $stmt->fetchAll();
return $result;
}
I want to use max to get the highest id on that table but my syntax doesn't work.
public function fetchBillingByParentId($db,$id) {
$select = $db->select('max(id)')->from('assignment_billing')->where('assignment_id = '.$id);
$stmt = $select->query();
$result = $stmt->fetchAll();
return $result;
}
Did I forgot something? the first syntax is working though. But in the second syntax it doesn't return any value? I think I have an error in 'select('max(id)')->' line. What might be the proper arrangement in this kind of syntax?
Anytime you use an aggregate you must alias the column.
$select = $db->select('max(id) AS balloon')->from('assignment_billing')->where('assignment_id = '.$id);
You would then reference balloon as the column.
I m creating function that process query and pass it's return result back. so I used following code:
function test(){
$query = "select * from mytable where id=123";
$data = mysql_query($query) or die(mysql_error());
return $data;
}
$info = test();
is it possible and can i use $info to get values as $info[0],$info[1]..
take a look at mysql_fetch_array function.
This function lets you iterate a query result which is a resource and turn each row into an array.Therefore you should use a while loop to get all rows in a resource;
You're missing one vital part, returning the result of mysql_query() just returns a result pointer not the dataset. You should add mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_row:
function test(){
$query = "select * from mytable where id=123 LIMIT 1";
$data = mysql_query($query) or die(mysql_error());
$result = mysql_fetch_row($data);
return $result;
}
$info = test();
now you can use $info[0], $info[1]. When using mysql_fetch_assoc you could use $info['fieldname'].
I also added LIMIT 1, since you're sending a long an ID, this probably is unique and after 1 result there is most likely nothing else to be returned.
You can do that, however it is better in my experience to keep the database stuff encapsulated, so you don't expose MySQL resources outside of the database context that then further need mysql_fetch_assoc() and the like on them.
I would use PDO there, and return the results of fetchAll(PDO::FETCH_ASSOC). That way, $info has the data it needs without needing to run further database functions on.
<?php
$link = mysql_connect('localhost', 'USERNAME', 'PASSWORD');
mysql_select_db('DB NAME', $link);
function test()
{
$result = mysql_query("select * from wp_options");
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
return $data;
}
echo "<pre>";
print_r(test());
echo "</pre>";
mysql_close($link);
?>
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
//$values = array();
while($row = mysql_fetch_array($result))
{
return 'gg';
return(array($row['member_id']));
}
}
Not able to get the userlevel field.... nor anything....
Not sure exactly what your question is, but one problem is that you're returning from within this while loop:
while($row = mysql_fetch_array($result))
{
return 'gg';
return(array($row['member_id']));
}
In fact, you're returning twice from within the loop... so the procLogin() function will always return a value of "gg", unless something goes wrong with your SQL query.
In general, you should avoid return statements within any loop, as it creates confusion and can lead to unexpected results.
return(array($row['member_id']));
Looks wrong - it should be:
return($row['member_id']);
You shouldn't need to define the array in the return like that.
You also use mysql_fetch_array () which returns as a numerical index - the function you probably want is mysql_fetch_assoc which is much nicer to work with as it returns the values with the keys as the column name rather than a numerical index.
Here's it again with a few tidy ups:
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['member_id'] > 0)
{
return ($row['member_id']);
}
else
{
return false;
}
}
I'm thinking, based on your comments about the userlevel, that you want to return the entire array rather than just the member_id ? Here's a slight edit to Meep3D's answer above:
function procLogin($username,$password){
$query = "SELECT *
FROM members
WHERE login = '".mysql_escape_string($username)."'
AND passwd = '".mysql_escape_string($password)."'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if (mysql_num_rows($result) > 0)
{
$row = mysql_fetch_assoc($result);
return $row;
}
else
{
return false;
}
}
This should return an array of all your table columns, if you are looking for the userlevel, presumably you should be able to access it something like:
$loginInfo = procLogin("theband","password1");
//if ($loginInfo) or something similar here
$level = $loginInfo['userlevel'];
So are you getting anything returned? That is to say, is it actually going into the while loop?
I'd use a mysql_error() function call straight after the mysql_query call to see if anything went wrong there.
Maybe there was no connection made, for example.
Are you still having issues? If so try something like:
echo $query;
after you define the query, then copy+paste that into phpmyadmin to check if there are any valid returns from the database.
After that try placing:
if (mysql_error())
{
trigger_error ("MySQL Error: ". mysql_error(), E_USER_ERROR);
}
Just after you call mysql_query. This should trigger an error if there is one giving you details of what went wrong.