How to store sql column name in form value - php

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.

Related

POSTING an ID from one table to another

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.

How to write an update SQL statement to update multiple records

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

Unable to insert multiple data into MYSQL database

I am unable to insert the data entered in the text box into MYSQL database. I am trying to insert inputs from multiple textboxes into the database.
<?php
include('questionDB.php');
if(isset($_POST['submit'])){
$questionID = $_POST['id'];
$answer = mysql_real_escape_string(htmlspecialchars($_POST['answer']));
mysql_query("INSERT INTO answers(question_id, answer_body) VALUES ($questionID, $answer)");
}
?>
<form name="auctionQuestion" method="post">
<?php
$auctionSurvey = "SELECT question_id, survey_id, question_body FROM questions
WHERE survey_id='1'";
$aucResult = mysql_query($auctionSurvey) or die (mysql_error());
while($auctionRow = mysql_fetch_assoc($aucResult)){
echo $auctionRow['question_body']. "<input type=\"text\" name=\"answer\"><BR>";
?>
<input type="hidden" name="id" value="<?php echo $auctionRow['question_id'] ?>">
<?php
}
?>
<input type="submit" name="submit" value="Submit">
</form>
Use either:
VALUES ('$questionID', '$answer')
or:
VALUES ('" . $questionID . "', '" . $answer . "')
instead of VALUES ($questionID, $answer)
First thing to do is to generate the correct HTML, so that you will get back arrays of variables.
I think it will be something like this
echo $auctionRow['question_body'] . "<input type=\"text\" name=\"answer[]\"><BR>";
Similar for the other fields.
Then, when you get the post in, use print_r($_POST) to see exactly what you have got. Go from there.

echoing to text box in php

I'm trying to do something simple to learn how to do a query and then put the answer into a box. I have a HTML file that looks like this:
<html>
<head>
<title>Test</title>
</head>
<body>
<form action="results.php" method="post">Search: <input name="term" type="text" /><br />
<input name="submit" value="Submit" type="submit" />
<p>Answer: <input name="answer" type="text" /></p>
</form>
</body>
</html>
And the php code is:
<?php
$hostname = 'host.com';
$username = 'ratetable';
$password = 'mypassword';
$term = (int) $_GET['term'];
try
{
$db = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
//echo 'Connected to database<br />';
foreach($db->query('SELECT * FROM rates WHERE mileage<= ' . $term . ' ORDER BY mileage DESC LIMIT 1') as $row) {
echo "<input type='text' name='answer' value='" . $row['ratepermile'] . "'>";
}
}
catch (PDOException $e) {
echo $e->getMessage();
throw($e);
}
?>
So I'm trying to put ratepermile, a field in the database, into the 'answer' text box. What I get is the screen clears, but no form and no result, even after I comment out the 'connected to database' echo line and use something that I know exists in the database.
How can I keep the form on screen and echo to the text box?
Thanks for looking.
Your form is POSTing the data (method="post"), but your PHP script is looking in the $_GET aray.
You need to get the data from $_POST instead.
$term = (int) $_POST['term'];
As well as the above POST issue. If you wish to keep the form on the page and not reload the page you need to look into AJAX.
You can use $_REQUEST in order to avoid these confusions. Whether you use method="post" or method="get", you can fetch the value through this.

Checkbox values into mysql query

i have this code which permits me to retrieve data from a checkbox, there isn't any mysql included yet, so can you help me modify this?
The form is like this:
<form action="checkbox.php" method="post">
<input type="checkbox" name="checkbox[]" value="hostess_name">
<input type="checkbox" name="checkbox[]" value="hostess_familyname_en">
<input type="checkbox" name="checkbox[]" value="hostess_id">
<input type="checkbox" name="checkbox[]" value="hostess_firstname_en">
<br>
<br>
<input type="submit" name="Submit" value="Submit">
</form>
The values i inserted are supposed to be database fields, then i have this checkbox.php file which reads the values selected.
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
echo "Connected to MySQL<br />";
?>
<?
/* and in your checkbox.php you do this: */
if(isset($_POST['Submit']))
{
echo "<pre>"; print_r($_POST);
}
$checked = mysql_real_escape_string(implode(',', $_POST['checkbox']));
echo $checked;
?>
How can assign to checkbox values database fields?
What i'm trying to do is to store the values and export them into a query using implode..
Help me..
Your POST variable ($_POST['checkbox']) is actually already an array. First, to figure out what you are actually working with, do this:
echo '<pre>';
print_r ($_POST['checkbox']);
echo '</pre>';
Then view your script and have a look at the output. Chances are you'll see an array with some keys and values. Using that you can decide how to proceed.
If it were me I would do something like the following to accomplish your task:
$sql = "SELECT `table_id_column`, `another_column` ";
foreach ($_POST['checkbox'] as $key => $value) {
$sql .= ", `$value`";
}
$sql .= " FROM `hostess` ORDER BY `another_colmn` ASC";
Please keep in mind that allowing an SQL statement to be modified in this manner is very bad practice. You'll want to introduce some security into this before putting it on a production environment.
Luke
Use
foreach($_POST[checkbox] as $key => $value {
echo PHP_EOL . "Key is => " . $key . " Value is => " . $value . PHP_EOL;
}
Try this and see the output, you'll see yourself how to proceed further.

Categories