I have two tables in db, input table nd output table. input table got two columns $ID (autoincreament), $question. table 2 got two columns $Q_ID, Answer.
i made a php page (1) where i printed out the table 1 content (QUESTION) and i added a text area to get answers from visitors, along with it i also added a echo "hidden" field for ID from table one.
Now this php page 1 redirects to php page 2, where i POST the text area input into the answer column in table 2. But unfortunately, the ID is not able to get posted in q_id column of table 2...
I tried a lot but no hope..
My PHP script #1 as follows::
<div class="name">
<?php
$sql = "SELECT * FROM input";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$index = 0;
while($row = $result->fetch_assoc()) {
$index++; // stuff inside foreach goes here
?>
<div id="q">
<B><big><font color= #ba4a00> Q:</font></big> <?php echo $row["question"]; ?>
<?php
echo '<button class="add" id="add_'.$index.'"><B>Add Answer</B></button>';
echo '<form style="display:none;" name="answer_'.$index.'" method="post" action="output.php">';
echo '<input type="hidden" name="questionid" value="<?php echo $row[id]?>"/>';
echo '<textarea type="text" class="addtext" name="addtext" required id="addtext_'.$index.'" placeholder="Please type your answer here.." ></textarea>';
echo '<button onClick="addsubmit('.$index.');" type="submit" id="addsubmit_'.$index.'" class="addsubmit"><B>Submit</B></button>';
echo '</form>';
?>
</div>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
</div>
My PHP script #2 as follows::
<?php include('1.php'); ?>
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "*******";
$dbname = "the_database";
$addtext = $_POST['addtext'];
$questionid = $_POST['questionid'];
$date = date_default_timezone_set('Asia/Kolkata');
$date = date('M-d,Y H:i:s');
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO output (question_id, answer, date)
VALUES ('$questionid', '$addtext', '$date')";
if ($conn->query($sql) === TRUE) {
echo '<script language="javascript">';
echo 'alert("Your Answer has been Succesfully posted")';
echo '</script>';
echo '';
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
i want the respective question id to be passed to table 2 along with its answer.
Any help is greatly appreciated..
Give single-quote in $row['id']. Change this <?php echo $row[id] >? to <?php echo $row['id'] >?
echo '<input type="hidden" name="questionid" value="'. $row['id'].'"/>';
Already you are echoing the form using the ECHO Attribute in the PHP but after that also you have echoed it and that is wrong.
You have to make the code like this.
echo '<input type="hidden" name="questionid" value="'. $row['id'].'"/>';
Try this and share the thought about the code..
try enclosing id in double quotes in php 1:
echo '<input type="hidden" name="questionid" value="'.$row['id'].'"/>';
yip... looking a this a bit more closely you've got a bit of a problem with mixing single and double quotes in PHP #1.
for example, on this line the echo command ends after the second single quote after add_
echo '<button class="add" id="add_'.$index.'"><B>Add Answer</B></button>';
You need to use either single or double quotes consistently.
Related
I have a table in data base with columns like ID,question,date. and an php page (1.php)which outputs question and date from db table and takes answer in textarea. when clicked submit, it redirects to another php page (2.php) where i m supposed to store the typed answer into another table in db.
here, my problem is how can i add question_ID to the second table in db along with answer.
1.PHP script as follows::
<div class="name">
<?php
$sql = "SELECT * FROM input";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$index = 0;
while($row = $result->fetch_assoc()) {
$index++;
?>
<div id="q">
<?php echo $row["question"]; ?> </B>
<?php
echo '<button class="add" id="add_'.$index.'"><B>Add Answer</B></button>';
echo '<form style="display:none;" name="answer_'.$index.'" method="post" action="output.php">'; // I dont think openning form from row to row would be nice!
echo '<textarea type="text" class="addtext" name="addtext" required id="addtext_'.$index.'" placeholder="Please type your answer here.." ></textarea>';
echo '<button onClick="addsubmit('.$index.');" type="submit" id="addsubmit_'.$index.'" class="addsubmit"><B>Submit</B></button>';
echo '</form>';
?>
<small><p><?php echo $row["date"]; ?></p></small>
2.PHP script as follows::
<?php include('1.php'); ?>
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "******";
$dbname = "the_database";
$addtext = $_POST['addtext'];
$date = date_default_timezone_set('Asia/Kolkata');
$date = date('d/m/Y H:i:s');
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO output (answer, date)
VALUES ('$addtext', '$date')";
if ($conn->query($sql) === TRUE) {
echo '<script language="javascript">';
echo 'alert("Your Answer has been Succesfully posted")';
echo '</script>';
echo '';
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Answer and date saved in db table successfully but got stuck in getting question_ID...
Any help is greatly Appreciated.
Add the hidden field:
on 1.php
echo '<form style="display:none;" name="answer_'.$index.'" method="post" action="output.php">'; // I dont think openning form from row to row would be nice!
echo '<input type="hidden" name="questionid" value="<?php echo $row[ID]?>"/>'
echo '<textarea type="text" class="addtext" name="addtext" required id="addtext_'.$index.'" placeholder="Please type your answer here.." ></textarea>';
echo '<button onClick="addsubmit('.$index.');" type="submit" id="addsubmit_'.$index.'" class="addsubmit"><B>Submit</B></button>';
echo '</form>';
on page 2.php
$qid = $_POST['questionid']; //get the question id and insert in the table
I am doing a project and need some help please :) (full code at bottom)
The project needs to be accessed with PDO.
I need search results to appear on the same page as the search was entered.
This below doesnt seem right to me using GET instead of POST.. is this correct?
This works but I need to remove/hide this bit of code that appears when my page (index.php) first loads.
if(!isset($_GET['search']))
{ echo "Error, Please go back."; exit;}
How do i do that?
Also my second problem is I can not get the search form to search more than one field in a table. It just wont let me. I cant use this bit of code either
%'.$searchterm.'%
as it wont give me any feedback from the search. So i am using the
:searchterm
in
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm OR nationality ");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
Here is my full code:
<?php
$servername = 'localhost';
$username = "root";
$password = "";
$dbname = "u1360138";
<?php
if(isset($_POST['search'])){
echo 'Search';
}
?>
<!-- Search facility 1 -->
<form action="index.php" method="get">
<label for="search">Enter a weight class. Need to be more than one searchs which wont work</label>
<input type="text" name="search" id="search">
<input type="submit" value="Search">
</form>
<?php
// DB Connection
try {$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);}
catch(PDOException $e)
{echo "Error conntecting to the DB: " . $e->getMessage();}
if(!isset($_GET['search']))
{ echo "Error, Please go back."; exit;}
// DB Connection
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{ echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>"; }
$conn=NULL;
?>
In good practices, use POST to send params when user SEND something to the server that will change data on the server (store in db for exemple or send an email). Use GET when user RETRIEVE something from the server, to read data (query a db). So prefer GET here.
To solve your issue, simply enclose the whole code that process the research in a "if(isset($_GET['search'])){}" section as below:
<?php
$servername = 'localhost';
$username = "root";
$password = "";
$dbname = "u1360138";
<?php
if(isset($_GET['search'])){
echo 'Search';
}
?>
<!-- Search facility 1 -->
<form action="index.php" method="get">
<label for="search">Enter a weight class. Need to be more than one searchs which wont work</label>
<input type="text" name="search" id="search">
<input type="submit" value="Search">
</form>
<?php
if(isset($_GET['search'])){
// DB Connection
try {$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);}
catch(PDOException $e)
{echo "Error conntecting to the DB: " . $e->getMessage();}
// DB Connection
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{
echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>";
}
$conn=NULL;
}
?>
This below doesnt seem right to me using GET instead of POST.. is this correct? This works but I need to remove/hide this bit of code that appears when my page (index.php) first loads.
It depends on whenever you want to use GET or POST. POST is more secure, so for submitting a form I'm always using POST. In that case you can leave this code:
if(isset($_POST['search'])){
echo 'Search';
}
You do need to change the form's action type to POST:
<form action="index.php" method="post">
....
Then add the end you need to get the search value from the POST instead of GET, because we changed the action type.
$searchterm = $_POST['search'];
So i figured this out and
<!-- HTML FORM SEARCH BAR -->
<form action="index.php" method="post">
<label for="enteredterm">Enter a Weight-class or a Nationality:</label>
<input type="text" name="enteredterm">
<input type="submit" name="search">
</form>
<!-- HTML FORM SEARCH BAR -->
if(isset($_POST['search'])){
$enteredterm = $_POST['enteredterm'];
if ($enteredterm ===""){
echo "error, enter something.";
} else {
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :enteredterm OR nationality LIKE :enteredterm or lastname LIKE :enteredterm ORDER BY year");
$stmt->bindValue(':enteredterm','%'.$enteredterm.'%');
$stmt->execute();
$count= $stmt->rowCount();
echo "You entered ".$enteredterm." and returned ";
if($count <= 1){
echo $count." result.";
}else{
echo $count." results.";
}
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{ echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>"; }
I'm new to php and MySQL (working through "Head First: PHP & MySQL"). I'm trying to grab a MySQL table column name from an array and store it in the "value" for an input field of a form. For some reason, I only end up with a blank page. When I simply type in some text into the 'value', the page turns out fine.
I've checked every line of code and have narrowed it down to the input value. The database connection works and I can echo the column name in the 'while' loop, but not in the 'value'.
Here's the code:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?> ">
<?php
$dbc= mysqli_connect('host', 'user', 'pass', 'elvis_store')
or die ('Error connecting to the database');
$query= "SELECT * FROM elvis_emails";
$result= mysqli_query($dbc, $query)
or die ('Error querying database');
while ($row= mysqli_fetch_array($result)){
echo '<input type="checkbox" value="'$row['Id']'" name="todelete[]" />';
echo $row['Id'];
echo ' ' . $row['first_name'];
echo ' ' . $row['last_name'];
echo ' ' . $row['email'];
echo '<br />';
}
mysqli_close($dbc);
?>
<input type="submit" name="submit" value="Remove" />
</form>
Thank you!
instead of,
echo '<input type="checkbox" value="'$row['Id']'" name="todelete[]" />';
try like this
echo '<input type="checkbox" value="'.$row["Id"].'" name="todelete[]" />';
What is really breaking the code is the missing of proper concatenation.
It's good practice to avoid printing HTML elements with PHP echo statement. Rather, the best approach in this case would be:
<?php while ($row = mysqli_fetch_array($result)){ ?>
<input type="checkbox" value="<?=$row['Id']?>" name="todelete[]" />
<?php
...
}
mysqli_close($dbc);
?>
If by anyways you do need to print a piece of code that is relying on HTML tags and PHP variables you can make use of HEREDOC instead of using echo to print multiple lines of code.
Also, make sure that you are naming the keys to the row array the
same as your query return values.
I have drop downs built by a PHP function pulling from MySQL tables. The drop downs work fine but the selected option isn't POSTing. I suspect the problem is with how the HTML select tag is created in PHP but I can't seem to find a way to correct it. I've searched around but nothing seems to work.
Here is the PHP function to build the drop down:
function contact_list(){
//Connection info
$dbhost = 'localhost';
$db = 'database';
$dbuser = 'user';
$dbpass = 'password';
//Define connection
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $db);
//Check connection
if (mysqli_connect_errno()) {
echo " ERROR " . mysqli_connect_error() . " ERROR ";
}
//Define search strings for drop down
$contact_list = "SELECT * FROM CONTACT_LIST";
//Execute search of primary_contact table
if (!mysqli_query($con,$contact_list)) {
die('' . mysqli_error($con));
}
//Return primary_contact results as string
$contact_result = $con->query($contact_list);
//Build drop down
echo "<select name='Primary_Contact'>";
//Loop through results
foreach ($contact_result as $row)
{
echo "<option value='' >" .htmlspecialchars($row['Primary_Contact']). "</option>";
}
echo "</select><p></p>";
}
Here is a sample of the HTML. The Description text box is fine so I don't think the problem is with the form tags.
<form action="mod_output_test.php" method="POST">
<u>Description</u>: <p></p>
<input type="text" name="Description" size="48" value="<?=$Description;?>"> <p></p>
<!-- Primary Contact -->
<?php echo "<u>Primary Contact</u>:<p></p>Current value: <b> " . $Primary_Contact . "</b>  New value: ";?>
<?php contact_list() ?>
<p></p>
<input type="submit">
</form>
Change
echo "<option value='' >" .htmlspecialchars($row['Primary_Contact']). "</option>";
to
echo "<option value='".$row['Id']."'>" .htmlspecialchars($row['Primary_Contact']). "</option>";
And I am guessing your dropdows is between a form tag.
in the top of the action file type this and tell us what you get
<?php
print_r($_REQUEST);
exit;
?>
echo "<option value='' >" .htmlspecialchars($row['Primary_Contact']). "</option>";
When you post like that, option value is empty. Add the id of the contact.
As they said, we see no <form> tag, we "assume" you add it before that piece. But the answer to "is not posting" is because value from <option> is empty.
I have this code so far, which reads a simple table with 3 varchar fields:
<?php
//db connection code...
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$query = "SELECT * FROM Sheet1";
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<html><body><table cellpadding=10 border=1>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['stickerID']."</td>";
echo "<td>" .$row['stickerName']."</td>";
echo "<td>".$row['stickerSection']."</td>";
echo "<td>"?>
<form name="some form" action="editform.php" method="post">
<input type="checkbox" name="<?php echo $row['stickerID'] ?>" value=" <?php echo $row['stickerStatus'] ?> ">
<?php "</td>";
echo "</tr>";
}
echo "</table></body></html>";
echo " " ?>
<input type="submit" name="editWish" value="Edit">
</form>
<?php " ";
} else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
The database has 4 fields, 3 varchar and 1 int with current value of 0. I checked the page source code and confirmed each checkbox name is the stickerID. Now I will post this to the editform.php which I must create. What Im wondering is how should I write the update sql so that it takes into account each new value selected by the user in the form?
This is my idea, but how to I do it for every checkbox?
editform.php
<?php
//update multiple records
//UPDATE user_items SET stickerStatus = $_POST["stickerStatus"] WHERE stickerID = $_POST["stickerID"];
?>
First question: use mysql_fetch_assoc() instead of mysql_fetch_row(). That will return an associative array instead of an enumerated one.
Second question: read up on HTML forms and form handling.
The answer to the question in the comments:
// The <form> tag should only be echoed once.
echo '<form name="some form" action="editform.php" method="post">';
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['stickerID']."</td>";
echo "<td>" .$row['stickerName']."</td>";
echo "<td>".$row['stickerSection']."</td>";
echo "<td>"?>
<input type="hidden" name="status_<?php echo $row['stickerID"; ?>" value="0">
<input type="checkbox" name="status_<?php echo $row['stickerID'] ?>" value="<?php echo $row['stickerStatus'] ?> ">
<?php "</td>";
echo "</tr>";
}
// You need a submit button to send the form
echo '<input type="submit">';
// Close the <form> tag
echo '</form>';
Using a hidden input with the same name as the checkbox makes sure a value for the given input name is sent to the server. The value of a checkbox that's not checked will not be sent. In that case the hidden input will be used.
You can get the submitted values in editform.php as follows:
<?php
foreach ($_POST as $field => $value) {
if (strpos($field, 'status_')) {
// Using (int) makes sure it's cast to an integer, preventing SQL injections
$stickerID = (int) str_replace('status_', '', $field);
// Again, preventing SQL injections. If the status could be a string, then use mysql_real_escape_string()
$stickerStatus = (int) $value;
// Do something with the results
}
}
Do
print_r($row)
to find out exactly how your row arrays are constructed and work from there.
For your comparison operator, use
$row[3] === 0
instead of
$row[3] == 0
This will return true if both the value and data type match rather than just the value.
0 can mean the Boolean false aswell as the numeric value 0