So I’am trying to add Php code to the database it works when I insert it in the database. But when I go to the browser the Php code I added was commented
code:
$insert = '</div> <br><br><br> <div class="posts-container"> <img src="'.$img.'" class="profpic"/> <div class="editB-cont"> <img src="img/editB.png" class="editB"/> </div> <h1>'.$sender.'</h1> <hr class="solid"> <p class="post-text-container">'.$post.'</p> <br><br> <img src="'."attatch/".$newfilename.'" class="attach"/> <br><br> <form action="post-comment" method="post"> <input type="hidden" name="parent-id" value="<?= echo $postId; ?>"> <input type="text" name="comment-text" placeholder="Comment..."> <input type="submit" value="Post" name="submit"> </form> <br> <div class="coments"> <?= include("get-comment.php"); ?> </div><br> </div><br><br> '; $sql = "INSERT INTO posts (sender, post, sender_id, image_attach, sender_img) VALUES ('$sender', '$insert', $id, 'attatch/$newfilename', '$img')"; if (mysqli_query($conn, $sql)) { header("Location: view-profile?id=$id"); } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } }
Is there any way to fix this?
Advertisement
Answer
Like Dharman said, $insert should be divided, so assign your include to a variable and then create $insert like so: ‘first part until div class=comments’ . $includeVariable . ‘second part’;
Regarding the sql injection, just google php prepared statements, or check this w3schools article https://www.w3schools.com/php/php_mysql_prepared_statements.asp
EDIT
in get_comment.php
$comment = 'just a test'; return $comment;
then
$includeVariable = include('get_comment.php'); $insert = 'first part' . $includeVariable . 'second part';
EDIT 2
You could try using eval() to display $insert or that commented part of it, HOWEVER as php manual states:
Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
This leads to another issue, probably the most important one: storing blocks of code like that in a database is a sign of a seriously bad design, you should think how to avoid it and rewrite you code rather than try to make it work
EDIT 3
Your PDO is wrong, in $link->prepare() number of database columns you insert into and number of inserted values must be the same, for example, I insert two values into two columns:
INSERT INTO user(name, age) VALUES (:name, :age)
which is same as
INSERT INTO user(name, age) VALUES (?, ?)
then you bind parameters
$statement->bind_param('si', $name, $age)
where ‘si’ are parameters types: (s)tring and (i)nteger, check https://www.php.net/manual/en/mysqli-stmt.bind-param.php for details
then assing values to you variables
$name = 'John'; $age = 44;
finally execute
$statement->execute();