贝壳 - BeiKe
贝壳 - BeiKe

Reputation: 113

How to pre-populate a form using the object-oriented approach of Mysqli?

I am trying to pre-populate a php form using the Object Oriented PHP Mysqli method. The examples I have found online are mostly procedural, and of no assistance. I can get the results to echo on the page, but once I try to use the echo tag in the input field it no longer works. The whole page is blank, and there are no errors.

$sql = "SELECT * from Pages where ID = 10";
$result = $mysqli->query($sql);
$row = array();


while ($row = $result->fetch_array()) {
    if (!empty($_POST['PTitle']) && $_POST['PTitle'] == $row['id']) {
        $selected = 'selected="selected"';
    } else {
        $selected = '';
    }
    echo '<option '.$selected.' value="'.$row["PType"].'">'.$row["PTitle"].', '.$row["PType"].', '.$row["PContent"].', '.$row["POrder"].', '.$row["PTitle"].'</option>';

}


//$mysqli->close();
?>  

<form>
  Name: <input type="text" value="<?php echo $row['PTitle]?>"/> </br>

</form>

Here is what I understood about it being outside the form, and while loop.

 require 'dor.php';

$sql = "SELECT * from Pages where ID = 10";
$result = $mysqli->query($sql);
$row = array();


while ($row = $result->fetch_array()) {
    if (!empty($_POST['PTitle']) && $_POST['PTitle'] == $row['id']) {
        $selected = 'selected="selected"';
    } else {
        $selected = '';
    }
    echo '<option '.$selected.' value="'.$row["PType"].'">'.$row["PTitle"].', '.$row["PType"].', '.$row["PContent"].', '.$row["POrder"].', '.$row["PTitle"].'</option>';


<form>
  Name: <input type="text" value="<?php echo $row['PTitle]?>"/> </br>

</form>

}


//$mysqli->close();
?>  

Upvotes: 0

Views: 173

Answers (1)

Sameer Kumar Jain
Sameer Kumar Jain

Reputation: 2135

Not sure what you are trying to achieve but you have many problems in your code, it must be something like this. It will print multiple input type and one select option if that is what you are trying to have

<?php
    require 'dor.php';

    $sql = "SELECT * from Pages where ID = 10";
    $result = $mysqli->query($sql);
    $row = array();
?>
<form>
<?php
    $options = '';     
    while ($row = $result->fetch_array(MYSQLI_ASSOC)) 
    {
        if (!empty($_POST['PTitle']) && $_POST['PTitle'] == $row['id']) 
        {
            $selected = 'selected="selected"';
        } 
        else 
        {
            $selected = '';
        }
        $options.='<option '.$selected.' value="'.$row["PType"].'">'.$row["PTitle"].', '.$row["PType"].', '.$row["PContent"].', '.$row["POrder"].', '.$row["PTitle"].'</option>';

?>
Name: <input type="text" value="<?php echo $row['PTitle']; ?>"/> </br> 
<?php
    }
?>  
<select><?php echo $options; ?></select>
</form>

Upvotes: 1

Related Questions