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 >
<label for="new-cat-title">New name of category</label>
<input value="<?php if(isset($cat_title)){echo $cat_title;} ?>" type="text" name="new-cat-title">
</div>
<div >
<input 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" name="new-cat-title">
CodePudding user response:
I'd do it like this (showing only the echo part inside the php code):
echo '<form action="categories.php" method="post">
<div >
<label for="new-cat-title">New name of category</label><input value="';
if(isset($cat_title)){echo $cat_title;};
echo '" type="text" name="new-cat-title"></div>
<div >
<input type="submit" name="submit" value="Rename Category">
</div>
</form>';
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.
CodePudding user response:
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.
CodePudding user response:
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:
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);
while($row = mysqli_fetch_assoc($edit_cat_query)) {
$cat_title = $row['cat_title'];
$cat_id = $row['cat_id'];
?>
<input value="<?php echo $cat_title; ?>" type="text" name="cat_title">
<?php
}
}
}