Comradeo Comradeo - 6 months ago 18
MySQL Question

Fetch mysql data from PHP using radiobutton control

I would like to manipulate PHP code to search for specfic data in the sql database that matched.

For example, let's say I want to search for an IP matched by a username in the sql database, they're all in the same rows, I select 'IP' in the radiobutton, input the username in the text field - My PHP code searches all for what's in the user database, finds the usernames, outputs only the ip address ( not anything else ), in the row titled 'IP Address' for that specific input. How would I go about doing this?

I want the radiobuttons to be a case, so if I select IP, it'll search IP matched by username, if I select UID, it'll search for UID matched by username and output it, and etc, etc.

HTML:

<form action="" method = "POST">
<input type="radio" name="someName" value="ip"> IP<br>
<input type="radio" name="someName" value="username"> Username<br>
<input type="radio" name="someName" value="uid"> UID
</form>


PHP:

<?php
error_reporting(E_ALL);
$con = new PDO('mysql:host='.$db_hostname.';dbname='.$db_database.';charset=utf8mb4', $db_termname,$db_password, array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
if(array_key_exists('term',$_REQUEST)){
$stm=$con->prepare('SELECT * FROM users WHERE username = ?');
$stm->execute(array($_REQUEST['term']));
while($row = $stm->fetch(PDO::FETCH_ASSOC)) {
echo $row['ip'];
}
}
?>

Answer

Your form should be like:

 <form action="" method = "POST">
      <input type="radio" name="someName" value="ip"> IP<br>
      <input type="radio" name="someName" value="uid"> UID<br>
      Enter Name: <input type="text" name="name" > <br>
      <input type="submit" name="submit"> Submit<br>
    </form>

and your php file :

    <?php
            error_reporting(E_ALL);
            $submit=isset($_POST['submit']);
            if($submit)  
{
              $name=$_POST['somename'];
              $username=$_POST['username'];
              $con = new PDO('mysql:host='.$db_hostname.';dbname='.$db_database.';charset=utf8mb4', $db_termname,$db_password, array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
              $stm=$con->prepare('SELECT * FROM users WHERE username = ?');
              $stm->bind_param("s",$username);
              $stmt->execute();
              $row = $stm->fetch(PDO::FETCH_ASSOC));
              if($name=='ip')
        {                       echo $row['ip'];  
        }
               else if($name=='uid')  
          {
                    echo $row['uid];
           }
 }