0

I am trying to fetch data from my DB but I am unable to do so. I sometimes do not get any result or sometimes I get failed without pressing the submit button. Please take a look into this code. I know there is something wrong I'm doing but I am unable to sort it out as I am a newbie and in learning process. Kindly take a look in my html and php. Although there is no error in connection with DB I have checked it thrice Its working fine to establisg connection with db. Here is my php code

<?php
if (isset($_POST['login']))
{
    include "config.php";
    $username=mysqli_real_escape_string ($conn,$_POST['user']);
    $password=$_POST['user'];
    $sql="SELECT username, password FROM user WHERE username='{$username}' AND password='{$password}'";
    $result = mysqli_query($conn,$sql) or die("Query failed");
    if (mysqli_num_rows($result)>0)
    {
       while( $row=mysqli_fetch_assoc($result))
       {
           echo "Successful";
       }
    }
    else
    {
        echo 'failed ';
    }
}

?>

My DB configures successfully, there's no error in config.php.

html is here

    <!DOCTYPE html>
<html class="no-js">
    <head>
        <meta charset="utf-8">
        <title>Login | Charity</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- Fonts -->
        <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,700' rel='stylesheet' type='text/css'>
        <link href='http://fonts.googleapis.com/css?family=Dosis:400,700' rel='stylesheet' type='text/css'>

        <!-- Bootsrap -->
        <link rel="stylesheet" href="assets/css/bootstrap.min.css">

        <!-- Font awesome -->
        <link rel="stylesheet" href="assets/css/font-awesome.min.css">

        <!-- Template main Css -->
        <link rel="stylesheet" href="assets/css/style.css">

        <!-- Custom Style -->
        <link rel="stylesheet" href="assets/css/login-style.css">
        
        <!-- Modernizr -->
        <script src="assets/js/modernizr-2.6.2.min.js"></script>


    </head>
    <body>
    <!-- NAVBAR
    ================================================== -->

    <header class="main-header">
        
    
        <nav class="navbar navbar-static-top">

            <div class="navbar-top">

              <div class="container">
                  <div class="row">

                    <div class="col-sm-6 col-xs-12">

                        <ul class="list-unstyled list-inline header-contact">
                            <li> <i class="fa fa-phone"></i> <a href="tel:">+123 456 789 </a> </li>
                             <li> <i class="fa fa-envelope"></i> <a href="mailto:contact@sadaka.org">contact@test.org</a> </li>
                       </ul> <!-- /.header-contact  -->
                      
                    </div>

                    <div class="col-sm-6 col-xs-12 text-right">

                        <ul class="list-unstyled list-inline header-social">

                            <li> <a href="#" target="_blank"> <i class="fa fa-facebook"></i> </a> </li>
                            <li> <a href="#" target="_blank"> <i class="fa fa-twitter"></i>  </a> </li>
                            <li> <a href="#" target="_blank"> <i class="fa fa-google"></i>  </a> </li>
                            <li> <a href="#" target="_blank"> <i class="fa fa-youtube"></i>  </a> </li>
                            <li> <a href="#" target="_blank"> <i class="fa fa fa-pinterest-p"></i>  </a> </li>
                       </ul> <!-- /.header-social  -->
                      
                    </div>


                  </div>
              </div>

            </div>

            <div class="navbar-main">
              
              <div class="container">

                <div class="navbar-header">
                  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">

                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>

                  </button>
                  
                  <a class="navbar-brand" href="index.html"><img src="assets/images/sadaka-logo.png" alt=""></a>
                  
                </div>

                <div id="navbar" class="navbar-collapse collapse pull-right">

                  <ul class="nav navbar-nav">

                    <li><a href="index.html">HOME</a></li>
                    <li><a href="about.html">ABOUT</a></li>
                    <li class="has-child"><a href="#">CAUSES</a>

                      <ul class="submenu">
                         <li class="submenu-item"><a href="causes.html">Causes list </a></li>
                         <li class="submenu-item"><a href="causes-single.html">Single cause </a></li>
                         <li class="submenu-item"><a href="causes-single.html">Single cause </a></li>
                         <li class="submenu-item"><a href="causes-single.html">Single cause </a></li>
                      </ul>

                    </li>
                    <li><a href="gallery.html">GALLERY</a></li>
                    <li><a href="contact.html">CONTACT</a></li>
                    <li><a class="is-active" href="login.html">LOGIN</a></li>

                  </ul>

                </div> <!-- /#navbar -->

              </div> <!-- /.container -->
              
            </div> <!-- /.navbar-main -->


        </nav> 

    </header> <!-- /. main-header -->
    

    <div class="main-container">

        
        <div class="login-content">

            <!-----start-main---->
            <div class="login-form">
                <div class="head">
                    <img src="./assets/images/gallery/thumb/employee-avatar.png" alt="Employee Avatar"/>
                    
                </div>

                <div class="login-header">
                    <p><span class="welcome-label">WELCOME </span><br>
                    <span class="description"> Logon to system for best experience</span></p>
                </div>

                <form class="input-form">
                    <li>
                        <input type="text" name="user" class="text" placeholder="Email" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}" ><a href="#" class=" icon user"></a>
                    </li>
                    <li>
                        <input type="password" name="" placeholder="Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Password';}"><a href="#" class=" icon lock"></a>
                    </li>
                    <div class="forgot-password-label">
                        <a href="/">Forgot Password?</a>
                    </div>
                    <div class="p-container">
                            <input type="submit" name="login" value="LOG IN" >
                            <div class="clear"> </div>
                    </div>
                    <div class="new-account-container">
                        <p><span class="no-account-label">Doesn't have account? </span><span class="create-account-label"><a href="/">Create One</a></span></p>
                    </div>
                </form>
            </div>
            <!--//End-login-form-->
        </div>


    </div>


    <footer class="main-footer">

        <div class="footer-top">
            
        </div>


        <div class="footer-main">
            <div class="container">
                
                <div class="row">
                    <div class="col-md-4">

                        <div class="footer-col">

                            <h4 class="footer-title">About us <span class="title-under"></span></h4>

                            <div class="footer-content">
                                <p>
                                    <strong>Sadaka</strong> ipsum dolor sit amet, consectetur adipiscing elit. Ut at eros rutrum turpis viverra elementum semper quis ex. Donec lorem nulla, aliquam quis neque vel, maximus lacinia urna.
                                </p> 

                                <p>
                                    ILorem ipsum dolor sit amet, consectetur adipiscing elit. Ut at eros rutrum turpis viverra elementum semper quis ex. Donec lorem nulla, aliquam quis neque vel, maximus lacinia urna.
                                </p>

                            </div>
                            
                        </div>

                    </div>

                    <div class="col-md-4">

                        <div class="footer-col">

                            <h4 class="footer-title">LAST TWEETS <span class="title-under"></span></h4>

                            <div class="footer-content">
                                <ul class="tweets list-unstyled">
                                    <li class="tweet"> 

                                        20 Surprise Eggs, Kinder Surprise Cars 2 Thomas Spongebob Disney Pixar 

                                    </li>

                                    <li class="tweet"> 

                                        20 Surprise Eggs, Kinder Surprise Cars 2 Thomas Spongebob Disney Pixar 

                                    </li>

                                    <li class="tweet"> 

                                        20 Surprise Eggs, Kinder Surprise Cars 2 Thomas Spongebob Disney Pixar  

                                    </li>

                                </ul>
                            </div>
                            
                        </div>

                    </div>


                    <div class="col-md-4">

                        <div class="footer-col">

                            <h4 class="footer-title">Contact us <span class="title-under"></span></h4>

                            <div class="footer-content">

                                <div class="footer-form" >
                                    
                                    <form action="php/mail.php" class="ajax-form">

                                        <div class="form-group">
                                            <input type="text" name="name" class="form-control" placeholder="Name" required>
                                        </div>

                                         <div class="form-group">
                                            <input type="email" name="email" class="form-control" placeholder="E-mail" required>
                                        </div>

                                        <div class="form-group">
                                            <textarea name="message" class="form-control" placeholder="Message" required></textarea>
                                        </div>

                                        <div class="form-group alerts">
                        
                                            <div class="alert alert-success" role="alert">
                                              
                                            </div>

                                            <div class="alert alert-danger" role="alert">
                                              
                                            </div>
                                            
                                        </div>

                                         <div class="form-group">
                                            <button type="submit" class="btn btn-submit pull-right">Send message</button>
                                        </div>
                                        
                                    </form>

                                </div>
                            </div>
                            
                        </div>

                    </div>
                    <div class="clearfix"></div>



                </div>
                
                
            </div>

            
        </div>

        <div class="footer-bottom">

            <div class="container text-right">
                Sadaka @ copyrights 2015 - by <a href="http://www.ouarmedia.com">Ouarmedia</a>
            </div>
        </div>
        
    </footer>




       
        
        <!-- jQuery -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="assets/js/jquery-1.11.1.min.js"><\/script>')</script>

        <!-- Bootsrap javascript file -->
        <script src="assets/js/bootstrap.min.js"></script>


        <!-- Template main javascript -->
        <script src="assets/js/main.js"></script>

        <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
        <script>
            (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
            function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
            e=o.createElement(i);r=o.getElementsByTagName(i)[0];
            e.src='//www.google-analytics.com/analytics.js';
            r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
            ga('create','UA-XXXXX-X');ga('send','pageview');
        </script>
    </body>
</html>
Khurram
  • 29
  • 5
  • 2
    **WARNING**: When using `mysqli` you should be using [parameterized queries](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and [`bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to add user data to your query. **DO NOT** use manual escaping and string interpolation or concatenation to accomplish this because you will invariably create severe [SQL injection bugs](http://bobby-tables.com/). Accidentally unescaped data is a serious risk. Using bound parameters is less verbose and easier to review to check you’re doing it properly. You missed one here. – tadman Oct 29 '20 at 20:15
  • 2
    **WARNING**: Writing an access control layer is not easy and there are many opportunities to get it severely wrong. Any modern [development framework](https://www.cloudways.com/blog/best-php-frameworks/) like [Laravel](http://laravel.com/) comes with an [authentication system](https://laravel.com/docs/master/authentication) built-in, and there are [authentication libraries](http://phprbac.net/) you can use. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and **never store passwords as plain-text** or a weak hash like **SHA1 or MD5**. – tadman Oct 29 '20 at 20:15
  • 1
    Note: The [object-oriented interface to `mysqli`](https://www.php.net/manual/en/mysqli.quickstart.connections.php) is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface where missing a single `i` can cause trouble. Example: `$db = new mysqli(…)` and `$db->prepare("…")` The procedural interface is an artifact from the PHP 4 era and should not be used in new code. Additionally the procedural interface has less rigorous error checking and reporting, frustrating debugging efforts. – tadman Oct 29 '20 at 20:16
  • 1
    Is this production code or for purely academic purposes? – tadman Oct 29 '20 at 20:16
  • 3
    **$password=$_POST['user'];** should be **$password=$_POST['pass'];** – nacho Oct 29 '20 at 20:22
  • It still doesn't echo anything neither successful nor failed – Khurram Oct 29 '20 at 20:31
  • Enable error reporting [How to get the error message in MySQLi?](https://stackoverflow.com/a/22662582/1839439) – Dharman Oct 29 '20 at 20:33

1 Answers1

0

The first thing i noticed in your code is:

$password=$_POST['user'];

You wont be able to connect correctly to your DB if your using the variable storing the user for the database password. Change it to what ever variable your using to store the DB pass.

Try this code. Add the info manually and look if there error. If it works then tweak it to work with your code:

<?php
/* Connecting to DB */

$ConnectionSQL = new mysqli ('localhost', 'put_user_db', 'put_pass_db', 'database_to_connect');

/*If connection error*/
if ($ConnectionSQL->connect_error) {
    die('Connection Error (' . $ConnectingSQL->connect_errno . ') '
            . $ConnectingSQL->connect_error);
}
/*If Connection succesfull, show host info*/
echo '<p>Connection established: '. $ConnectingSQL->host_info.'</p>';
echo '<p>Server '.$ConnectionSQL->server_info.'</p>';

Second thing: Put the value for name of the password in the html form. Your not putting anything. Example:

 <input type="password" name="password"

PHP code:

 $password= $_POST['password']; 
xJ0ReLx
  • 1
  • 3
  • Yes DB is connected properly. When I use simple form without css and animations it works fine but when I use that in my orignal page it stops working. I am adding the complete html of that page in my question. Kindly review that one. I will be thankful – Khurram Oct 30 '20 at 05:31
  • I added that in the post, please review. You don't have anything in the "name" value of the html form for the password, so your not passing the password value. – xJ0ReLx Oct 30 '20 at 16:12