While creating a group with user ids, I am checking if the entered id exists in database. If it exists, group should be created, if not it should pop out an error.
I am passing array with user ids to a function user_check, but it is not getting checked. Here is my code:
<?php
function user_check($user_id)
{
$u1 = mysqli_query($con, "SELECT uid from users where uid<>'" . $_SESSION['user_id'] . "'");
while ($row = mysqli_fetch_array($u1)) {
$users = $row['uid'];
echo "users" . $users;
$users1 = sort($users);
$users2 = sort($user_id);
printf($users1);
if ($user1 == $user2) {
echo "same";
} else {
echo "not same";
}
}
}
Given a list of user_ids (that you have validated/filtered already) you could write a function something like the following (untested):
function all_users_exist(array $user_ids, Mysqli $con)
{
$result_uids = [];
$ids = implode(',', $user_ids);
$sql = "SELECT uid from users WHERE uid IN ($ids)";
$result = $con->query($sql);
if($result)
while ($row = $result->fetch_array(MYSQLI_ASSOC))
$result_uids[] = $row['uid'];
sort($user_ids);
sort($result_uids);
return $user_ids == $result_uids;
}
Related
INTRO
I am trying to better understand my knowledge of Php and using classes to better prganise my code so this is just an exercise for a better understanding rather than a real world solution.
BRIEF
I am calling in a function from a class which I have just learnt to do but I want to know the best way to do something simple tasks like use the object in an IF statement.
SCENARIO
So for instance I am setting my classes like so:
class user
{
// Get users ID
function get_user_id()
{
global $conn;
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['id'] . ', '; }
}
}
// Get users name
function get_user_name()
{
global $conn;
$sql = 'SELECT name FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['name'] . ', '; }
}
}
}
$userId = new user;
$userName = new user;
I am then initializing in my classes like so:
<?php $userId->get_user_id(); ?>
<?php $userName->get_user_name(); ?>
and THEN I am wanting to performa simple task like show a user based on the value of their ID, the above will return 2 sets of results of 4 so id 1, 2, 3, 4 & Dan, Andy, Ryan, Aran
so I am performing a simple IF statement like so:
if($userId > 1){
echo $userName;
} else {
echo 'not working';
}
But it returns 'not working' - I am just wanting to better understand how to use the functions in a way that A works and B best practice.
It doen't look like you've understood OOP just yet.
These code examples should hopefully give you an introduction but as in other comments, read up on OOP. I struggled with it at first but keep at it!
Create your user class
This class represents a single user and the actions associated with a user, think of it as a blue print. It should only perform functions related to a user, it shouldn't keed to 'know' about anything else. For example, database functions sholud be done elsewhere.
class User {
private $id;
private $name;
function __construct($array)
{
$this->id = $array['id'];
$this->name = $array['name'];
}
function getId()
{
return $this->id;
}
function getName()
{
return $this->name;
}
}
Load all users into an array
$sql = 'SELECT * FROM user';
$result = $conn->query($sql);
$users = [];
while ($row = $result->fetch_assoc() ){
$users[] = new User($row);
}
// this array now contains all your users as User objects
var_dump($users);
// echo all user's details
foreach($users as $user) {
echo $user->getId();
echo ' - ';
echo $user->getName();
echo "\r\n";
}
Load a single user
$sql = 'SELECT * FROM user WHERE id = 1';
$result = $conn->query($sql);
if ($row = $result->fetch_assoc()) {
$user = new User($row);
} else {
exit('User ID does not exist');
}
// echo the user's ID and name
echo $user->getId();
echo ' - ';
echo $user->getName();
Resourses
Laracasts - https://laracasts.com/series/object-oriented-bootcamp-in-php
Search PHP OOP explained - https://www.google.co.uk/search?q=php+oop+explained
<?php
class user {
// Get users ID
function get_user_id() {
global $conn;
$data = array();
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row['id'] . ', ';
}
}
return $data;
}
// Get users name
function get_user_name() {
global $conn;
$data = array();
$sql = 'SELECT name FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'] . ', ';
}
}
return $data;
}
}
$userId = new user;
$userName = new user;
// all user ids
$all_ids = $userId->get_user_id();
echo '<pre>';
print_r($all_ids);
// all user name
$all_name = $userId->get_user_name();
echo '<pre>';
print_r($all_name);`enter code here`
Check first response from both function after use if condition
You are comparing object with 1 not the value returned by function get_user_id().
So instead of
<?php $userId->get_user_id(); ?>
<?php $userName->get_user_name(); ?>
Try
<?php $id=$userId->get_user_id(); ?>
<?php $name= $userName->get_user_name(); ?>
and then put in your condition
if($id > 1){
echo $name;
} else {
echo 'not working';
}
I will suggest you to replace echo with return statement.
call your class as an object
$userid = user();
$username = user();
you can also try something like this
class user
{
// Get users ID
function get_user_id($id = "")
{
global $conn;
// check if id is empty or not
if(!empty($id)) {
$sql = 'SELECT id FROM users WHERE id = '.$id;
}else{
$sql = 'SELECT id FROM users';
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['id'] . ', '; }
}
}
// Get users name
function get_user_name($name = "")
{
global $conn;
// check if name is empty or not
if(!empty($name)) {
$sql = 'SELECT name FROM user WHERE name = '.$name;
}else{
$sql = 'SELECT name FROM user';
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc() ){
echo $row['name'] . ', '; }
}
}
}
$userId = new user();
$userName = new user();
$userId->get_user_id(1);
$userName->get_user_name();
echo $userId;
echo $userName;
please make sure you sanitize the id and name before use
IN both get_user_id, get_user_name methods please
return $row = $result->fetch_assoc();
so, it will value comes in $userId, $userName and you can access it.
right now you return nothing so $user_id has null value so, it always goes in else condition.
Example
function get_user_id()
{
global $conn;
$sql = 'SELECT id FROM user';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$value = '';
while ($row = $result->fetch_assoc() ){
$value .= $row['id'] . ', ';
}
return $value;
}
}
I want show my message system user Profile name(If have) else show user name.
In my every code I used as below, which work well.
if (empty($pname)) $pname = $username;
But in below I cannot understand how to Return 'profile name else user name' in my "function getusername($userid)".
Here if I use return $row[0] at my "function getusername" Its show username, But I want to show Profile name and If profile name empty then show user name.
Get profile name/user name code:
function getusername($userid) {
$sql = "SELECT username,pname FROM users WHERE `id` = '".$userid."' LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$username = $row['username'];
$pname = $row['pname'];
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $row[0];
} else {
return "Unknown";
}
}
This code fetch a specific message
function getmessage($message) {
$sql = "SELECT * FROM mail WHERE `id` = '".$message."' && (`from` = '".$this->userid."' || `to` = '".$this->userid."') LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
// reset the array
$this->messages = array();
$row = mysql_fetch_assoc($result);
$this->messages[0]['id'] = $row['id'];
$this->messages[0]['title'] = $row['title'];
$this->messages[0]['message'] = $row['message'];
$this->messages[0]['from'] = $this->getusername($row['from']);
$this->messages[0]['to'] = $this->getusername($row['to']);
} else {
return false;
}
}
Use this
function getusername($userid) {
$sql = "SELECT username,pname FROM users WHERE `id` = '".$userid."' LIMIT 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)) {
$row = mysql_fetch_array($result);
$username = $row['username'];
$pname = $row['pname'];
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $pname;
} else {
return "Unknown";
}
}
The problem is with how you are returning the value.
Change:
if (empty($pname)) $pname = $username;
// Now here return $row[0] show only username But How to return pname else username?
return $row[0];
To:
if(empty($pname)) return $username;
else return $pname;
Also, it is suggested you use mysqli instead of mysql.
Can't you use something like this?
return isset($pname) ? $pname : $username;
This basically is: if $pname is set, then return $pname, else return $username
MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}
I have a private message system and I have this function that returns the IDs of all the users in the conversation (except the sender):
function findOtherUsersInConversation($conversation_id) {
$sender = findMessageSenderId($conversation_id);
$query = mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id = '$conversation_id' AND user_id !=$sender");
while ($row = mysql_fetch_array($query)) {
$user_id = $row['user_id'];
print_r($user_id);
}
}
print_r return the Ids (for instance id100 and id 101)like this:
100101//which is not what i'm trying to do
I have another function that find the username in the database so for each user id I would like to get their usernames in this format:
echo usernameFromId($user_id)// this should echo out all the username like this (user a, user b, user c)
I think I have to do a foreach loop but I can't think how.
Try this:
function findOtherUsersInConversation($conversation_id){
$sender = findMessageSenderId($conversation_id);
$query = mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id = '$conversation_id' AND user_id !=$sender");
$users = array();
while ($row = mysql_fetch_array($query)) {
$users[] = usernameFromId($row['user_id']); // fetch user name and add it to array
}
return implode(', ', $users); // return a string separated by commas
}
findOtherUsersInConversation(10); // conversation id 10
Try like this
function findOtherUsersInConversation($conversation_id) {
$sender = findMessageSenderId($conversation_id);
$query = mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id = '$conversation_id' AND user_id !=$sender");
$cnt=0;
while ($row = mysql_fetch_array($query)) {
$user_id = $row['user_id'];
if($cnt==0):
$comma_separated .=$user_id;
else:
$comma_separated .=",".$user_id;
endif;
$cnt++;
}
return $comma_separated
}
$getID=findOtherUsersInConversation(10);
$arrayID= explode( ',', $getID);// split string from comma(,)
print_r($arrayID);// print all ID's as you want
May this will Help you.
function findOtherUsersInConversation($conversation_id){
$sender = findMessageSenderId($conversation_id);
$query = mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id ='$conversation_id' AND user_id !=$sender");
$usernameArr = array();
while ($row = mysql_fetch_array($query)) {
$user_id= $row['user_id'];
array_push($usernameArr, usernameFromId($user_id));
}
$comma_separated = implode(",", $usernameArr);
echo $comma_separated;
}
If you want to view the array only for your Information try:
var_dump($array);
otherwise try it in a foreach to output your array:
foreach($array as $var){
echo $var;
}
I am trying to query my database and create values for later use in another function. My first function (get_users()) should query the requests database and find all users listed for the specific global_id - there will always be a maximum of 4 users for this query. Then I want to use a second function (get_results()) and insert the values that were retrieved from the first function (get_users()) into the second function. In other words, i need to put users1,2,3,4 into get_results($user1, $user2, $user3, $user4) in the second function.
Hoping someone can help! Here are my functions:
function get_users($global_id)
{
$result = mysql_query("SELECT user_purchased FROM requests WHERE global_id = '$global_id'");
$row = mysql_fetch_row($result);
$user1 = $row[0];
$user2 = $row[0];
$user3 = $row[0];
$user4 = $row[0];
}
function get_results($user1, $user2, $user3, $user4)
{
$result = mysql_query("SELECT * FROM results WHERE username != '$user1'
AND username != '$user2'
AND username != '$user3'
AND username != '$user4'
ORDER BY distance");
...more stuff to do here with the query
}
Thanks
Call the second function inside the first one:
function get_users($global_id)
{
$result = mysql_query("SELECT user_purchased FROM requests WHERE global_id = '$global_id'");
$count = 0;
while($row = mysql_fetch_array($result))
{
$user[$count] = $row;
$count++;
}
get_results($user[0],$user[1],$user[2],$user[3]);
}
function get_results($user1, $user2, $user3, $user4)
{
$result = mysql_query("SELECT * FROM results WHERE username != '$user1'
AND username != '$user2'
AND username != '$user3'
AND username != '$user4'
ORDER BY distance");
...more stuff to do here with the query
}
You can even simplify the get_results function to have one variable as an array instead of 4 varialbles
function get_results($users)
{
$result = mysql_query("SELECT * FROM results WHERE username != '".$users[0]."'
AND username != '".$users[1]."'
AND username != '".$users[2]."'
AND username != '".$users[3]."'
ORDER BY distance");
...more stuff to do here with the query
}
And you should call it like this in the first function
get_results($users);
Send the values as parameter to the another function.
function get_users($global_id)
{
$result = mysql_query("SELECT user_purchased FROM requests WHERE global_id = '$global_id'");
$row = mysql_fetch_row($result);
$user1 = $row[0];
$user2 = $row[0];
$user3 = $row[0];
$user4 = $row[0];
//now send
get_results($user1, $user2, $user3, $user4);
}