Display records from database - php

I'm trying to display some information stored in MySQL comments table to an input but I'm having issues with that. Input named enterComment inserts data to my DB and I want it to redirect back to showComment input.
HTML:
form action='takedata.php' method='POST'>
<input type='text' id='enterComment' name='enterComment' width='400px' placeholder='Write a comment...'>
<input type='submit' id='combuton' name='comButon' value='Comment!'>
<input type='text' id='showComment' name='showComment'>
</form>
PHP:
<?php include "mysql.php"; ?>
<?php
if (isset($_POST['comButon'])){
$enterComment = strip_tags($_POST['enterComment']);
if($enterComment){
$addComment = mysql_query("INSERT INTO comments(comment) VALUES('$enterComment')");
if($addComment==1)
//INSERT INTO showComment input;
}
}
?>

try this, and use mysqli instead of mysql
include "dbconnect.php";
if (isset($_POST['comButon'])){
$enterComment = strip_tags($_POST['enterComment']);
if($enterComment){
$addComment = mysqli_query($conn, "INSERT INTO comments(comment) VALUES('$enterComment')");
if($addComment) {
$sql = "select comment from comments order by id desc limit 1";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()) { ?>
<input type="text" value="<?php echo $row['comment']; ?>">
<?php }
}
}
}
your form
<form action='' method='POST'>
<input type='text' id='enterComment' name='enterComment' width='400px' placeholder='Write a comment...'>
<input type='submit' id='combuton' name='comButon' value='Comment!'>
<?php if(!isset($_POST['comButon'])) { ?>
<input type="text" value="">
<?php } ?>
</form>

Related

Using GET and Post method in the same page

As you can see I get the id from get method, the problem is when I using the $id to update the record it doesnt work but if I replace the $id with a number it works just fine, for example ($query = "UPDATE article SET title='$title_up', utitle='$utitle_up', text='$text_up', image='$image_up' WHERE id=2";)
PHP code:
$id = $_GET['id'];
$sql="SELECT * FROM article WHERE id = '$id'";
$result=mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
$image = $row['image'];
$title = $row['title'];
$utitle = $row['utitle'];
$text = $row['text'];
}
if(isset($_POST['update'])){
$title_up = mysqli_real_escape_string($conn, $_REQUEST['title']);
$utitle_up = mysqli_real_escape_string($conn, $_REQUEST['utitle']);
$image_up = mysqli_real_escape_string($conn, $_REQUEST['image']);
$text_up = mysqli_real_escape_string($conn, $_REQUEST['text']);
$query = "UPDATE article SET title='$title_up', utitle='$utitle_up', text='$text_up', image='$image_up' WHERE id='$id'";
mysqli_query($conn, $query);
if ($conn->query($query) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
HTML form code:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for='title'>Title: </label> <br>
<input type='text' id='title' name='title' value="<?php echo$title;?>"/> <br>
<label for='utitle'>UTitle: </label> <br>
<input type='text' id='utitle' name='utitle' value="<?php echo$utitle;?>"/> <br>
<label for='text'>Text: </label> <br>
<input type='text' id='text' name='text' value="<?php echo$text;?>"/> <br>
<input type='text' id='image' name='image' value="<?php echo$image;?>" /> <br>
<input type="submit" name="update" value="Update" />
</form>
Replace this line :
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
By this :
<form action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]);?>" method="POST">
EDIT :
$_SERVER["PHP_SELF"] // return just file
$_SERVER["REQUEST_URI"] // return file and GET parameters

Passing multiple variable through a form

I have the following code, the variable 'name' and 'project' need to go to session variables on submit, in this case the submit happens through an 'onchange'event. The 'name' variable is POSTed but not the 'project' variable. Any ideas where my issue is?
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<?php
$query = $conn->prepare("SELECT name, project FROM models.models where models.active = 'yes'");
$query->execute();
while($r = $query->fetch(PDO::FETCH_OBJ)){
echo "
<div class='swiper-slide'>
<input type='image' src='models/thumbs/",$r->name,".jpg' id='name' name='name' value='",$r->name,"' onchange='this.form.submit();'/>
<input type='hidden' value='",$r->project,"' name='project' />
</div>
";
}
?>
</form>
<?php
$query = $conn->prepare("SELECT name, project FROM models.models where models.active = 'yes'");
$query->execute();
while($r = $query->fetch(PDO::FETCH_OBJ)){
echo "
<div class='swiper-slide'>
<input type='image' src='models/thumbs/",$r->name,".jpg' id='name' name='name[]' value='",$r->name,"' onchange='this.form.submit();'/>
<input type='hidden' value='",$r->project,"' name='project' />
</div>
";
}
?>
How to access:
$names = $_POST['name'];
for($i=0;$i<count($names);$i++)
{
echo $names[$i]."<br>";
}

How do I run multiple SQL Queries using "if(isset($_POST['Submit'])){"

Trying to make a CRUD, everything works except my Update function. I feel like the problem is in the second sql query. When I click on submit it just refreshes and the change is gone. Can anyone show me how to find what I need to change/show me what to change?
<head>
<title>Update</title>
</head>
<body>
</form>
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<form action="" method="post">';
echo "Company: <input type=\"text\" name=\"CName\" value=\"".$row['CName']."\"></input>";
echo "<br>";
echo "Contact: <input type=\"text\" name=\"Contact\" value=\"".$row['Contact']."\"></input>";
echo "<br>";
echo "City: <input type=\"text\" name=\"City\" value=\"".$row['City']."\"></input>";
echo "<br>";
echo "<input type=\"Submit\" = \"Submit\" type = \"Submit\" id = \"Submit\" value = \"Submit\">";
echo "</form>";
}
echo "</table>";
} else {
echo "0 results";
}
if(isset($_POST['Submit'])){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
?>
Instead of building a form inside PHP, just break with ending PHP tag inside your while loop and write your HTML in a clean way then start PHP again. So you don't make any mistake.
Also you've to submit your $id from your form too.
Try this
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $id ?>" />
Company: <input type="text" name="CName" value="<?= $row['CName'] ?>" />
<br>
Contact: <input type="text" name="Contact" value="<?= $row['Contact'] ?>" />
<br>
City: <input type="text" name="City" value="<?= $row['City'] ?>" />
<br>
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</form>
<?php
} // end while loop
echo "</table>";
}
else {
echo "0 results";
}
Note: You are passing undefined variables into your update query. As you are submitting your form you must have to define those variables before you use them.
if (isset($_POST['Submit'])) {
$CName = $_POST['CName'];
$Contact = $_POST['Contact'];
$City = $_POST['City'];
$id = $_POST['id'];
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
that loop? ID primary key or not?
maybe u need create more key in table dealer like as_id
<input type="hidden" name="idform" value="$as_id">
in statment
if($_POST){
$idf = $_POST['idform'];
if(!empty($idf)){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where as_id=$idf";
$result = $conn->query($sql);
}
$conn->close();
}

Populate Radio buttons and submit value to query database

I am trying to learn programming and have to populate a set of radio buttons and submit what is selected to show records from a database. I have already done this with a selection list, but can't quite understand what I need to change to convert it to a radio buttons.
Selection list:
<?php
require_once("dbconn.php");
$sql = "SELECT staffName, staffID FROM staff";
$rs = mysqli_query($dbConn, $sql) or die ('Problem with query' . mysqli_error($dbConn));
?>
<form id="task9" action="task7.php" method="get">
<select name="staffID" id="staffID">
<?php
while($row = mysqli_fetch_array($rs)) {
$name=$row["staffName"];
$staffIden=$row["staffID"];
echo "<option value=".$staffIden.">".$name."</option>";
}
?>
<br><br>
<input type="submit" name="submit" method="get">
<input type="reset" name="reset">
</form>
Radio buttons (all I get is all the names and only One radio button):
<?php
require_once("dbconn.php");
$sql = "SELECT staffName, staffID FROM staff";
$rs = mysqli_query($dbConn, $sql) or die ('Problem with query' . mysqli_error($dbConn));
?>
<form id="task9" action="task7.php" method="get">
<input type = "radio" name="staffID" id="staffID">
<?php
while($row = mysqli_fetch_array($rs)) {
$name=$row["staffName"];
$staffIden=$row["staffID"];
echo "<option value=".$staffIden.">".$name."</option>";
}
?>
Hopefully this question is clear enough.
Try using below code.
<?php
require_once("dbconn.php");
$sql = "SELECT staffName, staffID FROM staff";
$rs = mysqli_query($dbConn, $sql)
or die ('Problem with query' . mysqli_error($dbConn));
?>
<form id="task9" action="task7.php" method="get">
<?php
while($row = mysqli_fetch_array($rs)) {
$name=$row["staffName"];
$staffIden=$row["staffID"];
echo "<label>";
echo "<input type='radio' name='staffID' value='".$staffIden."'/> ";
echo $name;
echo "</label><br/>";
}
?>
<br><br>
<input type="submit" name="submit" method="get">
<input type="reset" name="reset">
</form>
try this
<?php
require_once("dbconn.php");
$sql = "SELECT staffName, staffID FROM staff";
$rs = mysqli_query($dbConn, $sql)
or die ('Problem with query' . mysqli_error($dbConn));
?>
<form id="task9" action="task7.php" method="get">
<?php
while($row = mysqli_fetch_array($rs)) {
$name=$row["staffName"];
$staffId=$row["staffID"];
?>
<input type='radio' name='staffID' value='<?php echo $staffId ?>'/>
<?php echo $name; ?>
<br/>
<?php
}
?>
<br/><br/>
<input type="submit" name="submit" method="get">
<input type="reset" name="reset">
</form>
to add to what is there you will likely need to add either some code to your task7.php file to handle the database actions or if the file is task7.php you will need to add a block to the top of your file to handle the self-submitted form

If content exists in database, provide form to update it - else provide form to add new row

It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting

Categories