I’m trying to echo a piece of text with PHP nested in it, anyone know how? I’ve tried it like this:
function update_category(){
global $connection;
if (isset($_GET['edit'])) {
$edit_cat_key = $_GET['edit'];
$query = "SELECT * FROM categories WHERE cat_id = {$edit_cat_key }";
$edit_cat_query = mysqli_query($connection, $query);
echo '<form action="categories.php" method="post">
<div class="form-group">
<label for="new-cat-title">New name of category</label>
<input value="<?php if(isset($cat_title)){echo $cat_title;} ?>" type="text" class="form-control" name="new-cat-title">
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="submit" value="Rename Category">
</div>
</form>';
while($row = mysqli_fetch_assoc($edit_cat_query)) {
$cat_title = $row['cat_title'];
$cat_id = $row['cat_id'];
}
}
}
It prints: <?php if(isset($cat_title)){echo $cat_title;} ?>
I’ve tried it like this:
<input value="' . <?php if(isset($cat_title)){echo $cat_title;} ?> . '" type="text" class="form-control" name="new-cat-title">
3
Answers
Based on Johannes' answer I managed to figure out an answer. I need to close the PHP tags and instead of echoing the wished result, put it in the while loop.
Like this:
I’d do it like this (showing only the echo part inside the php code):
This echoes the two strings (in single quotes) and in between them the variable depending on the condition, keeping the double-quote pairs of the attribute values intact.
Echo is a php statement. You use it to display an output, as a string. What you need is, replacing
echo '
with?>
and</form>';
with</form><?php
. These closing(?>
) and opening(<?php
) tags let you decide which part of your document should be processed as PHP. So PHP will ignore the rest of the document.