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.
Related
I have a form by which i use to send mails to users.
<form method="post" action="/functions/mails/mailstomysql.php">
<?php
$sql="SELECT UserId, FatherName, FirstName FROM profiles";
echo "<div class='FieldTitle' style='display:none;'>To</div>";
echo "
<div class='ui segment'>
<div class='ui fluid multiple search selection dropdown'>
<input type='hidden' multiple name='ReceiverId[]' required>
<i class='dropdown icon'></i>
<input class='search' tabindex='0'>
<div class='default text'>To</div>
<div class='menu' tabindex='-1'>
"; // list box select command
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "
<option class='item' data-value='".$row['UserId']."' value='".$row['UserId']."'>$row[FirstName] s/o $row[FatherName]</option>";
}
echo "
</div>
</div>
</div>
?>
<input type="text" name="MailSubject">
<textarea type="text" name="MailContent"></textarea>
<input id="btnAddRecord" name="submit" type="submit" value="Send">
</form>
This is the SQL Statement that retrieve the data for above form:
$sql="SELECT UserId, FirstName FROM profiles";
And this is the mailtomysql.php file which insert the data into MySQL database.
$ReceiverId=$_POST['ReceiverId'];
$MailSubject=$_POST['MailSubject'];
$MailContent=$_POST['MailContent'];
$sql = "INSERT INTO mails (
`ReceiverId`, `MailSubject`, `MailContent`, `MailRead`, `MailDate`
)
VALUES (
'$ReceiverId', '$MailSubject', '$MailContent', '1', CURRENT_TIMESTAMP()
)";
if ($conn->query($sql) === TRUE) {
echo "Mail sent!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
The above code works awesome and perfect.
My Question
The above mailtomysql.php file insert the selected users from Multiple Selection Box and post the selected user ids to ReceiverId column which i do not want that, instead i want to have row for every selected user.
like:
Now
ReceverId
114, 265, 112
What i want
ReceverId
114
256
112
Why
If a user want to delete the mail then it will delete the mail and other users which are in that mail will not see the mail too because it is deleted by a user.
So once more my question is how to make mailtomysql.php file to make row for every selected users rather than having selected users ids in one row.
Edited:
I used the Semantic-Ui to select the options from the dropdown list, but it is not working.
On form side:
<form method="post" action="/functions/mails/mailstomysql.php">
<select multiple name='ReceiverId[]'>
<?php foreach ($conn->query($sql) as $row){
echo "<option class='item' data-value='".$row['UserId']."' value='".$row['UserId']."'>". $row['FirstName'] . "</option>";
} ?>
</select>
<input type="text" name="MailSubject">
<textarea type="text" name="MailContent"></textarea>
<input id="btnAddRecord" name="submit" type="submit" value="Send">
Make sure the value is set in the option and the name of the select is ReceiverId[].
On the receiving end, this will result into only one query...
$ReceiverIds = $_POST['ReceiverId'];
$values = "";
foreach($ReceiverIds as $receiver){
//don't forget some validation here...
//this is potentially unsafe too since the values are not properly escaped. Perform proper escaping here...
$values .= "('$receiver', '$MailSubject', '$MailContent', '1', CURRENT_TIMESTAMP()
),\n";
}
$values = rtrim($values, ",\n");
$sql = "INSERT INTO mails (
`ReceiverId`, `MailSubject`, `MailContent`, `MailRead`, `MailDate`
)
VALUES
$values";
$success = $conn->query($sql)
foreach($ReceiverId as $item){
$sql = "INSERT INTO mails (
`ReceiverId`, `MailSubject`, `MailContent`, `MailRead`, `MailDate`
)
VALUES (
'$item', '$MailSubject', '$MailContent', '1', CURRENT_TIMESTAMP()
)";
$success = $conn->query($sql)
}`
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 am having problem inserting multiple data into MYSQL database. With the code below, I am only able to insert the data I have input. Let's say there are 3 questions and I must submit 3 inputs, it only submitted the last one.
<?php
include('questionDB.php');
if(isset($_POST['submit'])){
$questionID = $_POST['id'];
$answer = mysql_real_escape_string(htmlspecialchars($_POST['answer']));
$insert = mysql_query("INSERT INTO answers(survey_id, question_id, answer_body) VALUES ('1','" . $questionID . "', '" . $answer . "')");
if ($insert){
echo "Success";
} else {
echo "Failed";
}
}
$startTimeAuc = mysql_query("SELECT startTime FROM questions WHERE survey_id='1'");
$startTime = mysql_fetch_assoc($startTimeAuc);
$startTime = ($startTime['startTime']);
$endTimeAuc = mysql_query("SELECT endTime FROM questions WHERE survey_id='1'");
$endTime = mysql_fetch_assoc($endTimeAuc);
$endTime = ($endTime['endTime']);
$currentTimeAuc =(date("Y-m-d H:i:s"));
if( ( $currentTimeAuc >= $startTime && $currentTimeAuc <= $endTime)){
?>
<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 "<p class=\"questions\">". $auctionRow['question_body']."</p>". "<input type=\"text\" name=\"answer\" class=\"answerField\"><BR>";
?>
<input type="hidden" name="id" value="<?php echo $auctionRow ['question_id'] ?>">
<?php
}
?>
<input type="submit" class="submit" name="submit" value="Submit">
</form>
</div>
<?php
}
?>
Few points:
1. your code is vulnerable to sql injection, use prepared data or SQLI/PDO
2. All your questions and answers are given the same name that's why you get only one inserted. Try giving them different names (using -1/-2/-3 sufix etc.), or if I make this, I would have 3 questions and 3 answers in the same record in database instead of inserting 3 times.
3. See below part. You need to add variables to both answer and id. Otherwise they are getting the same name.
<input type=\"text\" name=\"answer\" class=\"answerField\">
<input type="hidden" name="id" value="<?php echo $auctionRow ['question_id'] ?>">
New to PHP and reading through Robin Nixon's PHP, MySQL, Javascript book. I am having trouble with an example of inserting and deleting data using a PHP script, specifically with how the author uses $_POST.
The example is a pretty simple add records/delete records of books with multiple inputs. Here's the code:
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post('isbn');
$query = "DELETE FROM classics WHERE isbn='$isbn'";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br />" .
mysql_error() . "<br /><br />";
}
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$category = get_post('category');
$year = get_post('year');
$isbn = get_post('isbn');
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
echo "INSERT failed: $query<br />" .
mysql_error() . "<br /><br />";
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Category <input type="text" name="category" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
When you refer to an element in $_POST with if (isset($_POST['delete']) && isset($_POST['isbn'])), where delete and isbn are used as names multiple times, how does $_POST know which element to reference to delete? I assume that since you can only delete one record at a time, the element in the array will automatically point to the one that's already set. However, how does the second condition of isset($_POST['isbn']) know which "isbn" element to check for? Does the && make the $_POST['isbn'] "inherit" the correct row?
Thanks for the help! And apologies for any possible misuse of the vocab. Still getting used to everything.
Your question is actually well thought out. And the example given in the book seems quite sloppy to me. I am assuming in later chapters he will delve into the use of arrays in $_POST values. But anyway, here is the key to the functionality of the whole script:
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>
_END;
}
See that <form action="sqltest.php" method="post">? And see that closing </form>? And note that they are being rendered each time the for ($j = 0 ; $j < $rows ; ++$j) loop happens? There is one individual form element for each line. That is messy code, but it works. When one clicks submit on each individual listing, the wrapping form responds & parses the variables nested inside it.
Like I said, sloppy code. But works. And it’s because if you have 30 ISBNs listed this program will spit out 30 individually wrapped <form> items. Uggh! Seriously if the book does not address arrays later on in a way that addresses this face-palm of a coding mess find a new book.
Since there are multiple forms, the input elements of only one form are submitted.
So basically, sqltest.php receives only one array of $_POST containing ['delete'] and ['isbn'] with the corresponding values only once.
You can check this out by using print_r($_POST) in sqltest.php.
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.