I am still learning and I found that I can't run PHP within PHP, after reading into it makes sense why you cannot do it (D'oh!), what I am struggling to find is the correct way to do this.
I have two buttons which link to different modals, if I do not use them within a IF Statement they work as expected as soon as I add to the IF Statement it breaks the page. (obviously because I am trying to run php within php)
What I'm trying to get working is to show a different button depending on the result of a column called "status" in the MySQL table, if it equals 1 it will show the edit button if anything else it will show a check-out button. I need to pass the <?php echo $fetch['id']?>
to the data-target I'm not sure how to go about that.
<?php
$status_code = $fetch["status"];
if("$status_code" == "1")
{ echo '<button type="button" data-toggle="modal" data-target="#update_modal<?
php echo $fetch['id']?>"><span ></span>edit</button>';
} else
{ echo '<button type="button" data-toggle="modal" data-target="#checkout_modal<?
php echo $fetch['id']?>"></span>Check-Out</button>';
} ?>
Any help is much appreciated.
CodePudding user response:
You just need simple concatenation with the .
(dot) operator.
E.g.
echo '<button type="button" data-toggle="modal" data-target="#update_modal'.$fetch['id'].'"><span ></span>edit</button>';
...etc.
This is used to join any two string values (whether hard-coded literals or variables) together. What's happening here is your code is building a string from several components and then echoing it.
Documentation: https://www.php.net/manual/en/language.operators.string.php
CodePudding user response:
You don't need to run PHP inside PHP.
You may use a comma (or a dot):
<?php
if ($status_code == "1") {
echo '<button type="button" data-toggle="modal" data-target="#update_modal<'
, $fetch['id']
, '"><span ></span>edit</button>';
} else {
echo '<button type="button" data-toggle="modal" data-target="#checkout_modal'
, $fetch['id']
, '">Check-Out</button>';
}
Or using short tags:
<?php if ($status_code === '1') : ?>
<button type="button" data-toggle="modal" data-target="#update_modal<?= $fetch['id'] ?>">
<span ></span>edit</button>'
<?php else: ?>
<button type="button" data-toggle="modal" data-target="#checkout_modal<?= $fetch['id'] ?>">Check-Out</button>'
<?php endif; ?>
You can have conditions (and other expressions) in short tags:
<button
type="button"
data-toggle="modal"
data-target="#<?=
$status_code === '1'
? 'update_modal'
: 'checkout_modal'
?><?= $fetch['id'] ?>">
<?php if ($status_code === '1') : ?>
<span ></span>edit
<?php else: ?>
Check-Out
<?php endif; ?>
</button>
And concatenate strings with dots:
<?php
$dataTargetPrefix =
$status_code === '1'
? 'update_modal'
: 'checkout_modal';
?>
<button
type="button"
data-toggle="modal"
data-target="#<?= $dataTargetPrefix . $fetch['id'] ?>">
<?php if ($status_code === '1') : ?>
<span ></span>edit
<?php else: ?>
Check-Out
<?php endif; ?>
</button>