-1

I am working on a project where I need to enter comma separated values in a database field and then extract the data to use in if and else statement.

For example: in the database field user_status i have usernames like admin,admin1,admin2,admin3........etc. I want to use these values like:

$user_status = $row['user_status']; // database values of all the usernames
$username    = $_SESSION['username']; // username of the logged in user eg. admin

if($user_status == $username) // if session username matches with a username in the database field
{
  statements;
}else{
  statements;
}

I want to extract the comma separated database values from the database and match if the logged in user's username matches with one of many username's in the database. But I am not pretty sure how to do this. Please help me experts.

Laptop Medico
  • 22
  • 2
  • 10

2 Answers2

1

Create an array with explode and use in_array to check if the $username exists in the $user_status array.

<?php
$username    = $_SESSION['username'];
$user_status = explode(',', $row['user_status']);

if (in_array($username, $user_status)) {
    //...
}

http://php.net/manual/en/function.explode.php

http://php.net/manual/en/function.in-array.php

tino.codes
  • 1,512
  • 1
  • 12
  • 23
  • when I echo $user_status = explode(',', $uhs['pads_status']); it returns Notice: Array to string conversion in C:\xampp\htdocs\sites\ptc\member_ads.php on line 87 Array – Laptop Medico Nov 10 '15 at 12:33
  • You don't need to echo the variable assignment, just echo the function result, just use echo explode..... – arussell Nov 10 '15 at 13:02
  • @LaptopMedico Why would you echo the `$user_status`? What do you try to achieve? `$user_status` is an array, so you have to use `print_r` or `var_dump` to debug. Maybe you should update you question or better create a new one. – tino.codes Nov 10 '15 at 13:36
0

As an alternative solution you can search for the string encapsulated in comas

if (strpos($user_status, ','.$username.',') !== false) 
   echo 'user found';
else 
    echo 'not found';
arussell
  • 132
  • 6