Submit multiple arrays to mysql database php - php

Below is a form I am submitting once this form is submitted it will display a questionnaire. The hidden input type in the echo statement holds an array of question id's. the question text is printed out. Then a text box is created for the answer to be filled in and this will be passed through as an array of different answers - questionanswer[].
<form action="addanswers.php" method="post">
<fieldset>
<?php
$sql = "SELECT * FROM QUESTIONS WHERE QUESTIONNAIRE_FK = '$questionnaireid';";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$questionid = $row["QUESTION_ID"];
if($row["QUESTION_TYPE"] == "ff"){
echo "<input type='hidden' name = 'questionid[]' value = '".$questionid."'>".$row["QUESTION_TEXT"]." <input type='text' name='questionanswer[]''></br>";
}
}
?>
<input type="Submit" value="Submit">
</fieldset>
</form>
I am then trying to submitting the data entered into the text box to the database but I also want to be able to link the question id from the form to the question answer and submit both of them to the answers table of the database along with a questionnaire id. The answers table looks like this:
Answers(Answer_ID(PK), Answer_Text, Question_FK, Questionnaire_FK)
Below shows addanswers.php. At the minute I am able to add the answer to the database which is posted from the text box in the questionnaire. I am having difficulty linking the question id to the answer text to submit it to the answer table.
$questionanswers = $_POST['questionanswer'];
$questionids = $_POST['questionid'];
foreach($questionanswers as $qa){
$sql = "INSERT INTO ANSWERS (ANSWER_TEXT, QUESTIONNAIRE_FK) values ('$qa', '$questionnaireid')";
mysql_query($sql) or die(mysql_error());
}
Any help and advice on this issue would be greatly appreciated.Thanks in advance for your help.

Alright, I just wanted to make sure of your array structure, try this way:
$questionanswers = array_map('mysql_real_escape_string', $_POST['questionanswer']);
$questionids = array_map('mysql_real_escape_string', $_POST['questionid']);
foreach($questionanswers as $ind=>$ans){
$sql = "INSERT INTO ANSWERS (ANSWER_TEXT, QUESTIONNAIRE_FK) values ('$ans', '$questionids[$ind]')";
//$ind above contains index of the $questionanswers array-> 0, 1, 2
//since your $questionids index is also numeric and have the
//same number of array values, we can use this index to refer
//the corresponding $questionids
mysql_query($sql) or die(mysql_error());
}
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Related

Why aren't the values from my form inserting into the database?

I have the following form:
<form id ="classadderform" action="formsubmit.php" method="POST">
<input type ="checkbox" name="note" value = "Note1"></input>
<input type="submit" value="Click Me" style="width:300px;">
</form>
Upon submit, the code redirects to formsubmit.php. Part of the code there is the following:
$db = new mysqli("sql...byethost8.com", "b8_163//....(database info));
$id = $_SESSION['id'];
.......
if(isset($_POST['note'])){
if($id){
$db->query("UPDATE answers SET WordLevel = 'Difficult' WHERE user_id=$id"); //<<<UPDATES SUCCESSFULLY
$notevalue=$_POST['note'];
$db->query("INSERT INTO answers (user_id, ValueColumn) VALUES ($id,'$notevalue')"); //<<<<<DOESN'T UPDATE
The WordLevel column updates successfully, but the value of the input named note does not insert into the column titled ValueColumn. This was working in my code a few days ago but it somehow stopped working. I tried different iterations of single quotes around $id and $notevalue but nothing seems to resolve the issue.
Any help would be much appreciated!
Execute and clear before the second query.
O you can try concating queries together using semicolon
$db->query("FIRST QUERY ; SECOND QUERY");
If you dont need the output of first query.
PDO multiple query
mysqli multiple query
might also help real_query

Specifying ID in Mysqli query in php

I'm working on a CMS site, I've got blog posts that I store in a database. I can create, edit and delete them. There's an issue though when I want to edit them.
I can't specify the WHERE clause in the update query to match the id of the blog post I'm trying to edit!
Suppose I've got a blog post with an id of '5'.
If I write this code for it, it works exactly the way it should.
$sqledit = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
But I don't want to edit just blog post #5, I want to edit the blog post that I'm updating. It seems to me this should work,
WHERE id= $_POST[id]";
... but it doesn't.
That just throws me an undefined id error. But it shouldn't because I can delete blog posts the exact same way with this particular code:
$sqldel = "DELETE FROM `paginas` WHERE id= $_POST[id]";
This does allow me to.
The code below is on the blog page, the edit query is in its own edit.php page
if (isset($_POST['edit'])) // if pressed, execute
{
echo
'<br><br> <div class="blogscript">
<form action="edit.php" method="post">Edit your stuff<br>
<input type="text" placeholder='. $pagetitle . ' ><br><br>
<textarea id="message2" name="message"><p>' . $message . '</p></textarea><br>
<input type="submit" name="editsubmit" value="Confirm" />
<input type="hidden" name="id" value="' . $id . '">. </form></div>';
}
I look forward to any tips I should try out.
EDIT:
This is my edit.php page
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "";
$DB_name = "cmsbase";
$MySQLi_CON = new MySQLi($DB_host,$DB_user,$DB_pass,$DB_name);
if($MySQLi_CON->connect_errno)
{
die("ERROR : -> ".$MySQLi_CON->connect_error);
}
$sql = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $MySQLi_CON->error;
}
$MySQLi_CON->close(); //close connection
echo "<script>alert('Edited');location.href='index.php';</script>";
?>
EDIT: This is what the var_dump contains
In order for values to be present in $_POST, you need to have some element (e.g. <input>, <select>, <textarea>) inside your form with a name attribute set to the $_POST key you want.
You can add a hidden input to your form for id.
<input type='hidden' name='id' value='" . $id . "'>
Assuming you are getting the $message variable shown in that form code by selecting from your database, you should be able to get the id from there as well, or potentially from your $_GET if that is how you determine which post is being displayed.
(While this is not actually an answer, what I want to say does not fit in the comments)
Your line
$sql = "UPDATE paginas SET message='$_POST[message]' WHERE id= $_POST[id]";
Is horrific. This is the stuff of nightmares. Lets say that POSTed data in a form, is posted from a script from some robot somewhere, because I'm pretty sure you don't prevent XSRF in your code.
What if that script chose to post:
$_POST ==> array => message = "mwahahaha";
=> id = "1; DROP TABLE paginas;"
And you may think "how would they know my table name?" ,but that's easily found from other nefarious id inserts or other hacks on your code from other entry points which give a SELECT result, and many tables have common names such as "users" / "orders" / "baskets" / "touch-me" etc. (Ok well maybe not touch-me, but you get the idea).
Mysqli_real_escape_string() Could be used but thats only escaping quote marks and special characters, it does not mitigate SQL injection and compromise.
So, what should you do?
In this instance I want to draw your attention to PHP type juggling. Unlike many other languages, PHP has implied data types rather than specific data tyes, so a data type of "1.06" can be string and juggled to being a float as well.
Your id parameter in your MySQL is very probably a numeric integer value, so how can you be sure that the value of $_POST['id'] is also in integer rather than a SQL Instruction?
$id = (int)$_POST['id'];
This forces the value to be an integer, so
$id = (int)"1; DROP TABLE paginas;";
Is actually processed as $id = 1. Therefore saving you lots of compromised tables, spam rows and other nefarious rubbish all over your website, your database and your reputation.
Please take the following concept on board:
NEVER EVER TRUST ANY USER SUBMITTED CODE.
EVER

Re-populating / Editing HTML form inputs using MySQL Data

Being new to PHP and SQL, I have build a simple HTML form with 20 inputs, allowing users to enter specific data through input type=text or file. I have built a mysql database where this user data is inserted / saved. All is working, this is a major accomplishment for me.
I'm asking for help on this next step, I think this step would be called “edit”?
This step would allow users to recall the mysql data they entered, at a later time, to edit and save. Would like to have this recalled data injected directly into the original HTML form. Now, it seems necessary to have a method, (possibly a HTML form ”id “input), that calls from the data base, the specific record (including all 20 data inputs) that is associated with this user. Am I thinking correctly?
I'm asking for help / direction with simple yet detailed approach to solve this step. Note, my few attempts at this “edit” step, using some examples, have failed. I do not have a firm grasp of this PHP, yet have strong desire to become proficient.
This is a model, stripped down version of my current working code. I eliminated the $connection = mysql_connect.
This is the PHP I built, working great!
<?php
require('db.php');
if (isset($_POST['first_name'])){
$first_name = $_POST['first_name'];
$favorite_color = $_POST['favorite_color'];
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `form_data` (first_name, favorite_color, trn_date) VALUES ('$first_name', '$favorite_color', '$trn_date')";
$result = mysql_query($query);
if($result){
echo "<div class='form'><h1>First Name & Favorite Color POST to db was successfull.</h1>
<br/><h3>Click here to return <a href='https://jakursmu.com/tapcon_builder/tb_form_data_1.1.php'>TapCon Builder</a></h3>
</div>";
}
}else{
?>
This is the HTML user form, works great with the PHP script:
<div class="form">
<h1>First Name & Favorite Color "POST" to db Test</h1>
<form target="_blank" name="registration" action=" " method="post">
<p> First Name<input name="first_name" type="text" placeholder="First Name" /> </p>
<p> Favorite Color <input name="favorite_color" type="text" placeholder="Favorite Color" /> </p>
<p> <input type="submit" name="submit" value="Submit / Update to db" /></p>
</form>
</div>
Suppose the user queries the database using their “first_name”, when this “edit” step is completed, the final result will render / inject the users “first_name” and “favorite_color” back into the original HTML form. Does this make sense?
The database I created for this help post, looks like this:
database image
When a user wishes to edit their data, they can enter their "first_name", in a form text input, (im assuming?) where their "first_name" will be found in the data base. The ouutput result of this database query will be injected into the original form, ready for any user edit.
User Edit for: Results (in origingal form):
Jack Jack Black
Jeff Jeff Green
Randall Randall Red
So on.........
I hope this explanation makes sense where any experienced help or direction is offered.
Thanks for viewing!
just for practice purposes, but can look into prepared statements at you liesure time.
first create ur php file
<form method="post" action="edit.php">
<?php
//in ur php tag. select items from the row based on an id you've passed on to the page
$sql = "select * from 'form_data' where blah = '$blah'";
$result = mysqli_query($connection, $sql);
if($result){
$count = mysqli_num_rows($result);
if($count > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['firstname'];
$lname = $row['lastname'];
//you can now echo ur input fields with the values set in
echo'
<input type="text" value="'.$name.'" >
';//that how you set the values
}
}
}
?>
</form>
Finally you can run and update statement on submit of this you dynamically generated form input.
Also please switch to mysqli or pdo, alot better that the deprecated mysql.
look into prepared statements too. Hope this nifty example guides you down the right path...

how to perform sql command on html page with user input field, and show result on the same page

i write a command, or i fill up parameter value from user input field. click the button, send this command to php and send resultant value back to html to display.
for example. on html page :
select ___ from ____,
two available input field i fill up with "tablenameone" and "valueone". then, result will be printed on html text field on the same page.
what i do know is those value can be sent(perhaps) as in such format
$('input[name="talbename"]')
$('input[name="value"]')
example.com?tablename=tablenameone&value=valueone
and from php side i use
$sql="SELECT '$_GET['value']' FROM '$_GET['tablename']';
what i dont know is that....how exactly should i perform this in a click function? its for sure using ajax. but how can i produce example.com?tablename=tablenameone&value=valueone
and where should i put $('input[name="value"]')
thanks in advance :D
You must not use direct input in your queries as you will be open to SQL injection attacks.
$sql="SELECT '$_GET['value']' FROM '$_GET['tablename']';
Instead, use the following:
$column = $_GET['value'];
$table = $_GET['tablename'];
$sql = sprintf("SELECT %s FROM %s;",
mysql_real_escape_string($column),
mysql_real_escape_string($table));
Although you are still exposing too much "inside information" by giving people a page that tells them all of your table and column names!
Anyway, here is a complete example;
<form method="post" action="">
<fieldset>
<legend>Select Data</legend>
<p><label>Table<br>
<select name="table">
<option value="tblStudents">Students</option>
</select></label></p>
<p><label>Table<br>
<select name="column">
<option value="firstname">First Name</option>
<option value="lastname">Last Name</option>
</select></label></p>
<p><input type="submit" name="submit" value="submit">
</fieldset>
</form>
<?php
$connection = mysql_connect("servername:3306", "user", "password") or die ('Error connecting to mysql');
mysql_select_db("databasename");
$column = mysql_real_escape_string($_POST['column']);
$table = mysql_real_escape_string($_POST['table']);
$sql = sprintf("SELECT %s FROM %s;",
$column,
$table);
$result = mysql_query($sql) or die(mysql_error());
echo '<ul>';
while($row = mysql_fetch_array($result)) {
echo '<li>' . $row[$column] . '</li>';
}
echo '</ul>';
mysql_close($connection);
?>
Seeming as though noone has actually answered the question (although they are all good points, I will assume there is a reason for you doing this), I will answer:
$('form[name=formname]').submit(function(e){
e.preventDefault;
var tablename = $('input[name="tablename"]').val();
var value = $('input[name="value"]').val();
$.get("example.php?tablename="+tablename+"&value="+value, function(data){
$('body div').text(data);
})
});
PHP:
$sql=mysql_query("SELECT '$_GET['value']' FROM '$_GET['tablename']'")or die(mysql_error());
$sqlOutput = mysql_fetch_array($sql);
echo "<pre>";
print_r($sqlOutput);
echo "</pre>";
Obviously replace formname with your form name, body div with the name of the element you want the output to go in and all other identifiers replaced where seen fit. Then change the output in the PHP to suit your needs.
Again, do bear in mind the posts regarding SQLi, because you have yourself a very serious problem there.
You really want to make sure you are not open to SQL injection.
You could use mysql prepared statements
or
use the php function mysql_real_escape_string($_GET['value'])
Read this thread:
How can I prevent SQL injection in PHP?
I'm not sure what you mean by the click function.

Two different destination of submit in one form

I have one form which need to submit data into two different tables in same DB.
at past time, i have asked how to submit form into two tables, but it impossible.
Then, I try to submit this form use two submit buttons with different destination.
Could you give some advise to submit this form after click them?
Javascript:
function button1click() {
yourForm.action = "ajax1.php";
yourForm.submit();
}
function button2click {
yourForm.action = "ajax2.php";
yourForm.submit();
}
HTML:
<form action='' method='post'>
<input type='input' id='blah' name='blee' />
<button type='button' onclick='button1click()'>Button 1</button>
<button type='button' onclick='button2click()'>Button 2</button>
</form>
why dear ?
if($_POST['submit'])
{
$sql1="insert into table 1";
mysql_query($sql1);
$sql2="insert into table 2";
mysql_query($sql2);
}
This should work..
one submit button only. OK!
You can do this many different ways. Just because the data is on one form, doesn't mean it has to go into one table. Basically you need to learn how to write some server side code that parses the incoming data and puts it where it needs to be.
So the simplest way is to just submit your form, and then on the server save the data to where it needs to go.
Having 2 buttons could be clunky, unless thats how it was designed...
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("MYDB") or die(mysql_error());
// Insert a row of information into the table "example"
$sql="INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
// Insert a row of information into the table "example"
$sql=mysql_query("INSERT INTO example1
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
?>
You can insert into different tables like this:
EDIT (new code):
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("double") or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO example1
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
?>
Hope this answers you question because toy cant have double destination (i think) but this inserts into two different MySQL tables...
Good luck
To summarize what others have said above,
You could submit to two different locations, using javascript to change the action attribute of the form. You might wanna use it if the two destinations are not on the same server.
Or you could submit it to one destination only, massage your data, and then insert into two tables using php. It'll be particularly advantageous as you wouldn't need to sanitize or validate the data twice on server-side.
Very Very Simple...
You can insert in two tables by only one submit button..
Example:
<?php
if(isset($_POST['submit']))
{
$value1 = (!empty($_POST['form_name_value1']))?$_POST['form_name_value1']:null;
$value2 = (!empty($_POST['form_name_value2']))?$_POST['form_name_value2']:null;
$str = "INSERT INTO table_name1(db_value1, db_value2)VALUES('$value1','$value2')
$sql = mysql_query($str) or die(mysql_error());
$str1 = "INSERT INTO table_name2(db_value1, db_value2)VALUES('$value1','$value2')
$sql1 = mysql_query($str1) or die(mysql_error());
if($str)
{
echo "Successful";
}else{
echo "Unsuccessful";
}
if($str1)
{
echo "Successful";
}else{
echo "Unsuccessful";
}
}
This question was asked 4 years ago. Not the time to answer now I know. But
still answering to help others searching for the same problem.
Vote Up if you find this helpful. :D

Categories