-1

I have the following code where I worked with ´text files´. Here I say if the ´array´ is ´empty´ set user role to ´admin´ , if not set user role to ´user´. How can I do this when I store data to MySQL instead?

    $sajUsers = file_get_contents( 'users.txt' );
    $ajUsers = json_decode($sajUsers);

    // Create the JSON ONBJECT with key values
    if ( count( $ajUsers ) === 0 ) { // if the aray is empty create an Admin
    //echo( "The array is empty creating admin" );
    $jNewUser->role = 'admin';
    }  else { // if it´s not empty create a user
    //echo( "The array isnt empty creating user" );
    $jNewUser->role = 'user';
    }
codeDragon
  • 555
  • 1
  • 8
  • 28
  • the logic is the same: you populate a variable with "admin" or "user" and then you go on with query insertion with that variable. The query will be the same but will give different results based on what is the value of that variable – Lelio Faieta Dec 01 '17 at 12:29
  • Its not clear what are you trying to achieve. Just put the code that records the data inside the if statement? – Solmyr Dec 01 '17 at 12:30
  • I am focused on the if statement, here I check if the array in my text file is null or not and according to that I assign the role. How do I check if there is record in my table in MySQL? I tried mysql_num_rows, but it says `Can't use function return value in write context Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().` – codeDragon Dec 01 '17 at 12:35
  • Basically what I want is if there is no record in my table my first user will have the role admin, and all the rest that comes after will be users. So how to check that in MySQL? – codeDragon Dec 01 '17 at 12:38

1 Answers1

0
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

$sql = "your_select_query";

    if ($conn->query($sql) === TRUE) {
       echo "Success \n";
       $results= $conn->query($sql);
       /*do whatever you want with your data i.e. $results here*/
       } else {
         echo "Error \n" . $conn->error;
       }
Red Bottle
  • 2,839
  • 4
  • 22
  • 59