Home > OS >  How to fetch only 1 row from database
How to fetch only 1 row from database

Time:10-31

I want to fetch the id of only 1 row from my database for my change password. So that it will only change the password of that specific id selected. This code says an error, $id is undefined.

<?php
    $connection = mysqli_connect("localhost", "root", "", "ofad");


    $query = "SELECT * FROM admin WHERE id='$id' LIMIT 1";
    $query_run = mysqli_query($connection, $query);

    if(mysqli_num_rows($query_run) == 0 ){
        while($row = mysqli_fetch_assoc($query_run)){
    ?>

    <input type="text"  name="id" value="<?php echo $row ['id']; ?>" required>

    <div >
        <label>Current Password</label>
        <input type="password"  name="oldPass" placeholder="Current Password" required>
    </div>

    <div >
        <label>New Password</label>
        <input type="password"   name="newPass" placeholder="New Password" required>
    </div>

    <div >
        <label>Confirm New Password</label>
        <input type="password"  name="confirmPass" placeholder="Confirm New Password" required>
    </div>

    <div >
        <input type="submit" id="click" name="save_btn">
        <label for="click" >Save</label>
        <!--MODAL POPUP-->
    </div>
<?php
        }
    }      
?>

CodePudding user response:

If a user is logged in you start a session and use his credentials like e.g. the username here:

<?php
ob_start();
session_start();
$username = $_POST["username"];
$_SESSION["username"] = $username;
?>

Now you can query the ID belonging to the username on the following pages. Use prepared statements to prevent sql injections. Here is an example with mysqli. You have to adjust the column names to those of your admin table:

<?php
if (isset($_SESSION['username']))
{
$username = $_SESSION["username"];
$valueSearch = "";
$connection = mysqli_connect("localhost", "root", "", "ofad");
$stmt = $connection->prepare("SELECT `ID` FROM `admin` WHERE `username` = ?"); 
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt -> store_result();
$stmt -> bind_result($valueSearch);
$stmt->fetch();
$stmt->close();
mysqli_close($connection);
print $valueSearch;
}
?>

CodePudding user response:

all the problem is in $id, it has not variable to defined it, so add line before the SQL query defined the $id.

as example: $id = 5; (5 is your ID number in database)

another problem may appear to you in 'if' statement your condition is: if there is no rows run the while function

to resolve this, change the statement with
(mysqli_num_rows($query_run) != 0)

or (mysqli_num_rows($query_run) == 1) -- as you sure there is single row

  • Related