mercredi 29 avril 2015

PHP if statement within if statement

i'm building a php site where i want the user to create hes company.

The script is checking for the user has any companies registered already and then it should display information regards to where or not he has.

If he doesnt have registered hes company he should see a form where he can register.

If he choose to register company the script will check for any company with the same name or insert the row.

My only problem is that when there's already a company with that name the echo doesnt display.

I have written inside the code where the problem is.

<?php
        $con=mysqli_connect("mysql","USER","PASS","DB");
        if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }

            $result_get_companies = mysqli_query($con,"SELECT * FROM companies WHERE userid='". $login_session ."' ORDER BY companyid ASC") or die(mysqli_error());

            if (mysqli_num_rows($result_get_companies) >= 1) {

                while($row_companies = mysqli_fetch_array( $result_get_companies )) {

                $result_get_company_owner = mysqli_query($con,"SELECT username FROM users WHERE userid='". $login_session ."'")                 or die(mysqli_error());

                $company_owner = mysqli_fetch_assoc($result_get_company_owner);

                    echo 'THIS WORKS';
                }

            } else {

                if (isset($_POST['create_first_company']) && !empty($_POST['company_name'])) {

                    $company_name_unsafe = mysqli_real_escape_string($con, $_POST['company_name']);
                    $company_name = preg_replace("/[^a-zA-Z0-9\s]/","",$company_name_unsafe );

                    $check_companies = "SELECT companyid FROM companies WHERE company_name='". $company_name ."'";
                    $what_to_do_companies = mysqli_query($con,$check_companies);

                    if (mysqli_num_rows($what_to_do_companies) != 0) {

                        echo 'THIS DOESNT WORK
                                It does register that is should go here
                                because it does not insert new row.
                                and when the value is = 0 it does go
                                to else ELSE below and insert row.';

                    } else {

                        $result_create_company = mysqli_query($con,"INSERT INTO companies (companyname) 
                                                                    VALUES ('". $login_session ."')") 
                                                                    or die(mysqli_error());

                        echo 'THIS WORKS';  

                    }

                } else {

                    echo 'THIS WORKS!';

                }

            }

?>

Aucun commentaire:

Enregistrer un commentaire