how to combine the function to get the info of certain studid - php

heres my code
if(isset($_POST['select'])){
$studId = $_REQUEST['studid'];
foreach ($studId as $ch){
echo $ch."<br>";
}
}
//the result of this is like this
c-1111
c-1112
c-1113
// but i want to know their names
i have a function to get the studinfo shown below. how would i apply/insert this in the above code to get the names of those stuid's..pls help
function getuserinfo($ch){
$info_select = "SELECT `$ch` FROM `tbl_student` WHERE `studId`='$ch'";
if ($query_get = mysql_query($info_select)) {
if ($result = mysql_result($query_get, 0, $ch)) {
return $result;
}
}
}
$fname = getuserinfo('fname');
$lname = getuserinfo('lname');
$mname = getuserinfo('mname');

This is wildly dangerous as is, but here is the basic idea:
Your current query inexplicably fetches the student id where student id equals the passed value. So that looks like it is just trying to verify, but it is unnecessary. You want to return all info, then replace the first $ch with just * to fetch all...
function getuserinfo($ch){
$info_select = "SELECT * FROM `tbl_student` WHERE `studId`='$ch'";
if ($query_get = mysql_query($info_select)) {
if ($result = mysql_result($query_get, 0, $ch)) {
return $result;
}
}
}
You call it by passing the id:
getuserinfo($ch);
You can then access all student info for the row. try var_dump(getuserinfo($ch)) to see what's returned if this makes no sense.
But you are just fetching RAW from $_REQUEST with absolutely no cleansing. You are wide open to attack this way.
Switch to PDO or mysqli and use prepared statements. This answer is just to explain how ot get the info. In no way do I condone the use of these deprecated methods as is.
edit
As per your comment, you need to access the result to do something like that...
if(isset($_POST['select'])){
$studId = $_REQUEST['studid'];
$where = "";
foreach ($studId as $ch){
$where .= "studId = '$ch' OR";
}
if(strlen($where) > 0)
{
$where = substr($where, 0, -2);
$result = $mysqli->query("SELECT studId, CONCAT(fname, " ", mname, " ",lname) AS name FROM tbl_student WHERE $where");
while ($row = $result->fetch_assoc()) {
echo $row['name'].'<br>';
}
}
}
...again, sanitize the input. It's not being done in this example. This is just to give an idea

Related

Output multiple values from PHP function

I have created the following function to fetch data from my database, but its capabilities are limited. Currently it can fetch one value at a time, which is fine for fetching the value of one column of one row, but as I progress with my work, I now want to be able to fetch multiple values in one call.
The Function:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data[$value];
}
mysqli_close($connection);
}
How I currently use it to fetch multiple values:
// Define variables
$x1 = retrieve("x1");
$x2 = retrieve("x2");
$x3 = retrieve("x3");
$x4 = retrieve("x4");
$x5 = retrieve("x5");
$x6 = retrieve("x6");
$x7 = retrieve("x7");
$x7 = retrieve("x8");
I have read other questions here on Stack Overflow, but none of them solves my problem as I use an optional parameter, which makes my life hard. For example, I thought of implementing the splat operator to allow unlimited parameters, but as I use the optional parameter $identifier, I can't make it into something like:
function retrieve($identifier = null, ...$value) {}
because it will use the first parameter as the identifier when I omit it.
I'm sure that regarding performance it would be better if I could fetch all the necessary values in one call of the function retrieve() instead of using it as shown above and that's why I would like to know:
How can I edit this function in order to fetch more values at once?
Calling it like so:
$x = retrieve($y);
$x1 = $y["x1"];
$x2 = $y["x2"];
...
EDIT:
Thanks to Manish Jesani for his help! I used his answer and modified to do exactly what I want. For anyone that may be interested in the future, here's the code:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$values = array();
$identifier = (is_null($identifier)) ? "`ID` = '1'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if (is_array($value)) {
foreach($value as $_value) {
$values[$_value] = $data[$_value];
}
return $values;
}
else {
return $data[$value];
}
}
mysqli_close($connection);
}
You can call the function with as many parameters you want. Τo do this you have to use func_num_args() to get all of them, as shown below:
function retrieve() {
$args = func_num_args();
$query = "SELECT '".implode("','", func_get_args())."' FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data;
}
mysqli_close($connection);
}
You can call this function like this: $params = retrieve('x1','x2','x3').
Alternatively, you can retrieve them as variables list($x1, $x2, $x3) = retrieve('x1','x2','x3').
Please try this:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$return = array();
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if(is_array($value))
{
foreach($value as $_value)
{
$return[$_value] = $data[$_value];
}
}
else
{
$return[$value] = $data[$value];
}
return $return;
}
mysqli_close($connection);
}
$x = retrieve(array("x1","x2","x3","x4","x5","x6"));

How to use one query if _GET isn't exist and use other query if it is?

I want something strange. If someone opens index.php page, $select must be full, . But if someone opens index.php?var=4 page, $select must be other, with var from _GET.
I have this code now, but it works only if ?var=3 exists.
What am I missing?
foreach($_GET as $name=>$value)
{
if($name == 'lvl') {
$value = mysql_real_escape_string($_GET[lvl]);
$select = mysql_query("SELECT * from $table where lvl='$value'");
}
else {
$select = mysql_query("SELECT name,image,lvl,team,icon FROM $table");
}
}
while ($row = mysql_fetch_array($select))
{
$name = mysql_real_escape_string($row['name']);
You are depending on the existence of a ?lvl=... in your code.
Also, using the mysql-functions is not recommended, since they are deprecated. Consider changing to mysqli or PDO. For this example, I'll still use mysql-functions.
Better to use this:
if (isset($_GET['lvl'])) { // Check to see whether or not lvl is set in url
$value = mysql_real_escape_string($_GET['lvl']);
$select = mysql_query("SELECT * FROM $table WHERE lvl = '$value';");
} else { // If not, use other query
$select = mysql_query("SELECT name, image, lvl, team, icon FROM $table;");
}
while ...

Making a function to query the Database

I am writing a script to access a specific detail about the user and I was hoping to make the database query be function.
function connectUser($ip) {
$q = "SELECT * FROM users where ID='$ID'";
$s = mysql_query($q);
$r = mysql_fetch_array($s);
}
But when I try and use it it will not access the row the way I want it to.
$user = '999';
connectUser($user)
echo $r['name'];
But if I put echo $r['name']; in the function it will work.
your function is not returning anything. add return $r['name'] at the end of function.
then echo connectUser($user);
thare are 2 major problems in your code
the function doesn't return anything and you don't assign it's result to a variable.
Your variables doesn't match. $ip doesn't seem the same variable with $ID
so, this one would work
function connectUser($id) {
$q = "SELECT * FROM users where ID=".intval($id);
$s = mysql_query($q);
return mysql_fetch_array($s);
}
$user = '999';
$r = connectUser($user)
echo $r['name'];
That's because the variable $r isn't being returned by the function, so it's never being set outside of the function. Here's what you should have:
function connectUser($ip) {
$q = "SELECT * FROM users where ID='$ip'";
$s = mysql_query($q);
return mysql_fetch_array($s);
}
And then outside have:
$user = '999';
$r = connectUser($user)
echo $r['name'];
You might also want to take a look at this question: prepared statements - are they necessary
This function is not working,
as you did not supplied the database connection into function,
and you did not return anything (PHP will return NULL)
Please understand what is variable scope first,
and the function
A workable example, can be like :-
function connectUser($db, $ip)
{
$q = "SELECT * FROM users where ID='$ID'"; // vulnerable for sql injection
$s = mysql_query($q, $db); // should have error checking
return mysql_fetch_array($s); // value to be returned
}
How to use :-
$db = mysql_connect(...);
$res = connectUser($db, "some value");

PHP: Making this grabbing from db easier/simpler way?

Is there any method i could do this easier:
$query = mysql_query("SELECT full_name FROM users WHERE id = '$show[uID]'");
$row = mysql_fetch_array($query);
echo $row["full_name"] . " ";
as i only need to grab the full_name, then i make a var for the fetch_array and so, is there any way to make this simpler and echo? There was something about list(), but im not sure..
Ignoring possible security breaches and the usefulness of a DAL (see #deceze's answer), I recommend the use of mysql_result() instead of mysql_fetch_assoc() (or *_array() or whatever):
$query = mysql_query("SELECT full_name FROM users WHERE id = '$show[uID]'");
$fullName = mysql_result($query, 0);
echo $fullName . " ";
Not easier per se but should be more in line with the intention of the query (fetch one field in one row).
The only way to abstract this any more and thereby make the actual call shorter is by using a DAL and/or ORM like Doctrine or Propel, which you should anyway.
May be not easier, but more securely:
$id = mysql_real_escape_string($show['uID']);
$query = mysql_query("SELECT `full_name` FROM `users` WHERE id = '".$id."'");
$row = mysql_fetch_array($query);
echo $row['full_name'];
Oh you can to make id with intval:
$id = intval($id);
This could make further DB-questions easier;
function mysql_fetch_scalar($res)
{
$arr = mysql_fetch_array($res);
return $arr[0];
}
$query = mysql_query("SELECT full_name FROM users WHERE id = '".intval($show[uID])."'");
$fullname = mysql_fetch_scalar($query);
echo $fullname . " ";
Sure.
Moreover, you should - to make a function out of these repetitive API functions calls.
Something as simple, as this
function dbgetvar($query){
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res);
if (!$row) return "";
return $row[0];
}
have this function in your config file and use every time you want a value from database:
echo dbgetval("SELECT full_name FROM users WHERE id = '$show[uID]'");
(I hope you have $show[uID] escaped)
Of course there can be also 2 similar functions, to return a row or a rowset. Or just one but with additional parameter. Or you can combine them into class...
You can make it even escape variables for you:
function dbgetvar(){
$args = func_get_args();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
if (!$query) return false;
$res = mysql_query($query);
if (!$res) {
trigger_error("dbget: ".mysql_error()." in ".$query);
return FALSE;
}
$row = mysql_fetch_row($res);
if (!$row) return "";
return $row[0];
}
echo dbgetvar("SELECT full_name FROM users WHERE id = %s",$show['uID']);
That's what you have to do. You could wrap that in a helper function if you're using it a fair bit, but then you'd probably want to cache the answer you get - I don't suppose the name changes all that often...
function echoName($user_id) {
$id = mysql_real_escape_string($user_id);
$query = mysql_query("SELECT full_name FROM users WHERE id = '$id'");
$row = mysql_fetch_array($query);
echo $row["full_name"] . " ";
}
// ...
echoName($show['uID']);

Delete command Issue in PHP

I have a similar problem with delete command too..
function deleteUsers($userID) {
foreach($userID as $key => $val)
{
$query = "DELETE FROM members WHERE member_id = '$val'";
$result = mysql_query($query);
}
//$query = "DELETE FROM members WHERE member_id = $userID";
//$result = mysql_query($query);
if($result)
{
return 'yes';
}
}
its not performing multi delete.... the $userID contains array. Its not going inside the Query.
When using multiple IDs use variable IN (1,2,3) format rather than simple equality. Also if you have more than one ID maybe the variable should be called $userIDs?
if(count($userID) > 0) {
$query = 'DELETE FROM members WHERE member_id IN ('. implode(',', $userID) .')';
}
Without foreach:
function deleteUsers($userID) {
if (count($userID)) {
$query = "DELETE FROM `members` WHERE `member_id` IN (".implode(",", array_values($userID)).");";
if (mysql_query($query)) { return true; }
}
return false;
}
This will make the function to understand array as well as single integer:
function deleteUsers($u) {
$condition = is_array($u)
? "member_id IN (" . implode(',', $u) . ")"
: "member_id = " . (int)$u;
$res = mysql_query("DELETE FROM `members` WHERE $condition");
return $res ? true : false;
}
Remember that your parameters are not properly escaped and cannot be trusted. To learn more on escaping SQL and preventing injection attacks read about Prepared Statements.
Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Categories