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

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']);

Related

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

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

mysql_field_name to the new mysqli

I have a way to get the name of the columns of a table. It works fine but now I want to update to the new mysqli ? (I tried the mysqli_fetch_field but I don't know how to apply to this case and I am not sure if it is the wright option)
How to do the same with mysqli ? :
$sql = "SELECT * from myTable";
$result = mysql_query($sql,$con);
$id = mysql_field_name($result, 0);
$a = mysql_field_name($result, 1);
echo $id;
echo $a;
This is the way to implement this missing function:
function mysqli_field_name($result, $field_offset)
{
$properties = mysqli_fetch_field_direct($result, $field_offset);
return is_object($properties) ? $properties->name : null;
}
I'm not sure if there is a better way to do that, but I checked that this works to get just the name of the columns and is the new mysqli :
$result = mysqli_query($con, 'SELECT * FROM myTable');
while ($property = mysqli_fetch_field($result)) {
echo $property->name;
}
You can replace the function mysql_field_name to mysqli_fetch_field_directand use it like the following:
$colObj = mysqli_fetch_field_direct($result,$i);
$col = $colObj->name;
echo "<br/>Coluna: ".$col;
This is another easy way to print each field's name, table, and max length
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("Name: %s\n",$fieldinfo->name);
printf("Table: %s\n",$fieldinfo->table);
printf("max. Len: %d\n",$fieldinfo->max_length);
}
// Free result set
mysqli_free_result($result);
}
$sql = "SELECT * FROM myTable LIMIT 10";
$ressult = $con->query($sql);
$rows = $result->fetch_all(MYSQLI_ASSOC);
$fields = array_keys($rows[0] ?? []);
echo json_encode($fields);
Can return empty array if query returned no rows.

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 - how to use array in function?

I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function

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