inserting data from multiple text boxes to single column - php

enter image description herei want to insert multiple text box value in to a single column in a table at a time
it should b like there should be name and infront of name there are text boxes to enter age of the students
so when we submit then the age entered infront of the student name it will get stored in the table with student names and ages.
(multiple students data feeding at a time)

Hi Try this change table name and column name according to yours.
Also i have query all data of table this will update all fields age if already age exist and you fill again in form. So either apply where condition in your query so that it filter only name which does not have price or add value field in form which display age if exist in database.(This is according to code you provided in comment)
<?php
$conn = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password,$mysql_database) or die("Could not connect database");
$result = mysqli_query($conn,"select * from user");
if(isset($_POST['submit'])){
$sql = "UPDATE user SET age = (CASE name ";
foreach($_POST['age'] as $key=>$value){
$sql = "UPDATE user SET age = '$value' where name = '$key'";
mysqli_query($conn,$sql);
}
$success = "updated successfully";
}
if(isset($success) && !empty($success)){
echo '<h3>'.$success.'</h3>';
}
echo '<form method="post">';
echo '<table>';
while($row = mysqli_fetch_assoc($result)){?>
<tr>
<td><input type="text" value="<?php echo $row['name']; ?>" name="name" readonly="true"></td>
<td><input type="number" name="age[<?php echo $row['name']; ?>]" placeholder='enter age'></td>
</tr>
<?php } ?>
<tr><td colspan="2">
<input type="submit" name="submit" value="Save"></td></tr>
</table>
</form>

I didn't get your example but if you want to store multiple values in a single database column, you can pass these values into an array and encode it with json_encode. After reading the values from the database you can transform it back to an array with json_decode.

Use json_encode to encode the content and then store it in database field and when you retrieve the value then use json_decode
$form_data_json = json_encode( $_POST );

Related

Printing of data

I created 3 tables in my database "Colleges" in PhpMyAdmin. The names of the tables are "cool", "data" and "tab". The first table "cool" consists of the the names of the states of India. It has two columns : ID and Statename. From the data in this table, I created a drop down list in HTML form. Further the HTML form consists of the name, email id, contact and the address. The user has to fill in the details and select his/her state from the drop down list. Now, the user input consisting of name, email id, contact and the address goes into the second table "data" and the selected state from the drop down list goes into the 3rd table "tab", "tab" consists of 2 columns ID and stat where the state name gets stored here. I joined the above two tables "data" and "tab" using inner join of SQL. When I fetched the data in another web page, the name, email id, contact and address are getting printed but not the the statename. Instead of the state name, ID of the statename (as given in table cool) is getting printed.
I want state name to get printed.
Here is the drop down list created using the data from my database :
<td>State :</td>
<td>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'colleges');
$resultset = $mysqli->query("SELECT ID, Statename from cool");
?>
<select name="state">
<?php
while($rows = $resultset->fetch_assoc())
{
$ID = $rows['ID'];
$Statename = $rows['Statename'];
echo "<option value='$ID'>$Statename</option>";
}
?>
</select>
</td>
</tr>
And what are the changes to be done here to insert the selected dropdown state name into the table in my database ?
<?php
$connection = mysqli_connect("localhost", "root", "", "colleges");
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$address = $_POST['address'];
$state = $_POST['state'];
if($name !=''||$email !=''){
//Insert Query of SQL
$insert = "INSERT Into data(student_name, student_email, student_contact, student_address) values ('$name', '$email', '$contact', '$address')";
$query = mysqli_query($connection, $insert);
$insert2 = "INSERT Into tab(stat) values ('$state')";
$query2 = mysqli_query($connection, $insert2);
echo "<br/><br/><span>Data has been inserted successfully</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank</p>";
}
}
mysqli_close($connection); // Closing Connection with Server
?>
3). The printing part:
<?php
$hostname = "localhost";
$dbname = "colleges";
$username = "root";
$password = "";
$conn = mysqli_connect("$hostname","$username","","$dbname");
if(mysqli_connect_errno())
{
echo "Failed to Connect MySQL (phpmyadmin) Database: ".mysqli_connect_error();
}
$query = ("select student_name, student_email, student_contact, student_address, stat from data t2 inner join tab t3 on t2.ID=t3.ID");
$result = mysqli_query($conn, $query);
echo "<center>";
echo "<h1>Student list</h1>";
echo "<hr/>";
echo"<table border = '1'>
<tr>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
<th>Address</th>
<th>State</th>
</tr>";
while ($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['student_name']."</td>";
echo "<td>".$row['student_email']."</td>";
echo "<td>".$row['student_contact']."</td>";
echo "<td>".$row['student_address']."</td>";
echo "<td>".$row['stat']."</td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
mysqli_close($conn);
?>
echo "<option value='$ID'>$Statename</option>";
and
$state = $_POST['state'];
and
$insert2 = "INSERT Into tab(stat) values ('$state')";
You are actually not inserting the name of the state, but it's id, as the select return the selected option's value, not it's content. You can either change the first line to
echo "<option value='$Statename'>$Statename</option>";
which is a weird solution, or just use a join in your mysql query to get the statename
JOIN ON cool.ID = tab.stat
Extention:
When you use select, the innerHTML of option is displayed, but the value is sent in POST. So if you write
<select name="state">
<option value="1">name</option>
</select>
You will see name name, but the 1 will be sent.
On the next page, $State = $_POST['state']; will have $State the value of '1'. In the SQL you put this value to your stat field in your database, with a generated ID. It means, your ID won't hold any data, but the state field will!
So when printing on the third page, you have to join the list of states by it's ID with the stored stateid in the 'state' field. Then you will be able to print the statenames.
"SELECT * FROM t2 LEFT JOIN t3 ON t2.?? = t3.?? LEFT JOIN t1 ON t1.ID = t3.state"
Or something similar. Do you have a field you can use to join the t2 and t3 tables? It seems you are losing data when inserting to your database.

query form data to be passed on

I have a SQL table structured that way:
Id_value | id_group_value | name_group_value | name_value
I build a php/sql query to create a dropdown form getting its values which work like that:
<label>item</label>
<?php
$result = $conn->query("select id_ value,id_ group _ value, name _ group_ value, name_value FROM table WHERE id_ group _ value = 0");
echo "<select name='name_value' ><option value='' disabled selected>choose value</option>";
while ($row = $result->fetch_assoc()) {
unset($idv, $namev);
$idv = $row['id_value'];
$namev = $row['name_value'];
$id_gv = $row['id_group_value'];
$id_v = $row[' name_group_value '];
echo '<option value="'.$ idv.'">'.$namev.'</option>';
}
echo "</select>";
I can easily save values from that select form item using a '$_POST[form_item]' which I do this way and means get the $idv variable:
$sql = "INSERT INTO table (form_select_value)
VALUES ('$_POST[name_value]')";
What should I do to save another extracted value which I retrieved from the original SQL query, let’s say $namev variable, together?
Using hidden fields you can set all the values like:
<input type="hidden" name="nvalue" value="<?php echo $namev; ?>>"
And insert value like this,
$sql = "INSERT INTO table (form_select_value1,form_select_value2) VALUES ($_POST['name_value'],$_POST['nvalue'])";

PHP + MySQL Creating a form to change data in MySQL tables

I want to build a form to change the data in MySQL table. Firstly, I list all the data in the adminindex.php page. Then, I create a button to open the selected data in a form. I've done assigning the form fields to the main (pk) MySQL table. My problem started there when I need to fetch the foreign table data as the table contains many foreign data. As you guys know, a class may have many students, I have created the fields for class data, now the problem is in students data. Do I have to create many fields to fetch the data from MySQL foreign tables? If yes, could you guys guid me the code steps ? Thank you very much. Really appreciate your help :D
These are my steps:
Firstly I echo the rows, then I codes the form actions. Then, in adminpost.php, I create variables, link the fields and use UPDATE MYSQL to update the data in tables. I've succeeded in updating the primary table data but I'm stuck in foreign key data. Thanks :D
Have 2 pages. Display data in a form in first one and have update in the second. Here is a code for doing it one by one, you can build on it for multiple rows at a time if you want to.
edit.php
<?php
mysql_connect('ip', 'username', 'password') or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = mysql_query("SELECT * FROM table1 where order by question_id limit 1") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$id = $row['id'];
$value1= $row['value1'];
$value2= $row['value2'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?php echo $id;?>">
Value1: <input type="text" name="value1" value="<?php echo $value1;?>">
<br>
Value2: <input type="text" name="value2" value="<?php echo $value2?>">
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
update.php
<?php
mysql_connect('ip', 'username', 'password') or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$id = mysql_real_escape_string($_POST["ID"]);
$value1 = mysql_real_escape_string($_POST["value1"]);
$value2 = mysql_real_escape_string($_POST["value2"]);
$query="UPDATE table1 SET value1 = '.$value1.', value2 = '.$value2.' WHERE id='$id'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($id) Record Updated<p>";
}else{
echo "<p>($id) Not Updated<p>";
}
?>
Next
Might help to put your actual code up, but as i understand you are just wanting to edit the data that is already in your table? If thats the case :
//Connect to SQL DB
$dbcnx = #mysql_connect("localhost", "root", "password");
//Select DB
mysql_select_db("database_name", $dbcnx);
//Query DB
$sql = update table_name set column_name = "$variable" where column = "your_criteria";
#mysql_query($sql)
That will connect you to your SQL DB and update the records for you, hope thats what you needed

Displaying user's SQL query using PHP

Please can anyone help me with this?
I have 2 tables, location and tickets and what I have built so far is a form in a div that users enter the name of the city or town where they would like to see a live music performance. This form is submitted and an SQL statement is passed querying the location table. In another div, the users search query appears in a box on the screen. What I would like to do next is to write an SQL statement that will lookup the user's query and dynamically display the relevant ticket information from the ticket table based on the location ID.
For example, the user types in 'Newcastle' as their search query, the location table finds the city of Newcastle and displays the user's result in a div called 'tickets'..I would like to display all the fields that correspond with 'Newcastle' from the ticket table.
The locationID is the primary key in the location table and has 3 other column, city, town and postcode.
The ticket table consists of ticketID being the primary key, the locationID being the foreign Key and the other fields i.e venue, tPrice, date and time. I think the problem im having is im not passing through the variable from the users query so that the ticket table can look it up and display the relevant information.
Here is the code for the form:
<div id="search">
<form name="searchForm" id="searchForm" class="searchForm" method="post">
<input type="text" name="citySearch" id="citySearch" class="citySearch" placeholder="Enter name city/town..." autofocus="autofocus" />
<input type="submit" name="ticketSearch" id="ticketSearch" class="ticketSearch" value="Search" />
</form>
</div>
Here is the code to display the user's query:
<div id="locationResult">
<?php
include( 'classes/database_connection.php' );
$cSearch = $_POST['citySearch'];
$sql = "SELECT DISTINCT city FROM location WHERE city = '$cSearch'";
mysql_query($sql) or die (mysql_error());
$queryresult = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($queryresult)) {
$city = $row['city'];
echo $row["city"];
}
mysql_free_result($queryresult);
mysql_free_result($qResult);
mysql_close($conn);
?>
</div>
</div>
This is where I want to display the ticket results from the ticket table:
<div id="ticketsResults">
<table class="ticketResult" border="0" cellspacing="5">
<tr>
<td><b>Venue</b></td>
<td><b>Price</b></td>
<td><b>Date</b></td>
<td><b>Time</b></td>
<td><b>Street View</b></td>
</tr>
<?php
include( 'classes/database_connection.php' );
$locID = $_POST['locationID'];
$citySearch = $_POST['citySearch'];
$sQL = "SELECT locationID FROM location";
//Here is where I want it to display dynamic information rather than manually type the location
$ticketSQL = "SELECT * FROM ticket NATURAL JOIN location WHERE city = 'Newcastle' ";
mysql_query($sQL) or die (mysql_error());
$qResult = mysql_query($sQL) or die(mysql_error());
mysql_query($ticketSQL) or die (mysql_error());
$result = mysql_query($ticketSQL) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
// $ticketID = $row['ticketID'];
$venue = $row['venue'];
$ticketPrice = $row['tPrice'];
$date = $row['date'];
$time= $row['time'];
echo "<tr>\n";
echo "<td>$venue</td>\n";
echo "<td>&pound$ticketPrice</td>\n";
echo "<td>$date</td>\n";
echo "<td>$time</td>\n";
echo "<td>Click to see</td>\n";
echo "</tr>\n";
}
mysql_free_result($qResult);
mysql_free_result($result);
mysql_close($conn);
?>
</table>
</div>
So basically, I'm wanting an SQL statement that dynamically displays the tickets according to the user's query. Sorry about the copious amount of code! Any help given is greatly appreciated.
Before you do anything else I think you should work on your coding style, specifically your indentation. A quick google search should do the trick. Next look into mysql prepared statements because currently your code is unsafe. Like jordanm said, it is subject to SQL injection.
For example, if someone entered blah' OR 'x'='x as a city name. Your query would become
SELECT DISTINCT city FROM location WHERE city = 'blah' OR 'x'='x';
Basically it allows the user to do naughty things with your query, and you don't want that.
Below is a sample of how you can avoid this using mysql prepared statements:
// basic quick raw example
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare('SELECT DISTINCT city FROM location WHERE city = ?');
$stmt->bind_param('s',$city_name);
$stmt->execute();
$stmt->bind_result($city);
while ($stmt->fetch())
{
echo $city;
}
That's all I'm going to leave you with because I feel like to answer the actual question (?) I will need to write the code for you. Goodluck

how to insert an hidden field value along side with a checkbox in to the database

i am new here but i have a problem in inserting the id and the value of the checkboxes into my database here is the code of the form:
<?php
include('db.php');
$sql = "select * from sheet1 order by course_level asc";
$r = mysqli_query($dbc,$sql) or die(mysqli_error($dbc));
$co = '';
while($row = mysqli_fetch_array($r)) {
$co .= '<tr><td>'.$row['course_level'].'</td><td><input name="courses[]"
type= "checkbox" value = "'.$row['course_code'].'">'.$row['course_code'].'
</td> <td>'.$row['course_title'].'</td><td>'.$row['course_lecturer'].'
</td><input type=hidden name=cid[] value="'.$row['cid'].'">
</tr>';
}
?>
And this is the action code:
<?php
include('db.php');
if(isset($_POST['courses']))
echo 'lie';
else
echo 'true';
foreach($_POST['courses'] as $row=>$id){
$courses=$id;
$cid = $_POST['cid'][$row];
$sql = "insert into selected_courses values ('','$courses','$cid')";
$r = mysqli_query($dbc,$sql);
}
if($r)
echo 'done';
?>
thanks a lot.
You have several problems here, the main one being you are attempting to store two different reference values to the same row (course_code and cid) in your selected_courses table. You should really only store the primary key (cid?).
I'd suggest dropping the course_code column from your selected_courses table, remove the hidden input and structure your checkbox like this
<input type="checkbox"
name="courses[]"
value="<?php echo htmlspecialchars($row['cid']) ?>">
Then your INSERT query simply becomes
// Forget mysqli, move to PDO
$stmt = $dbc->prepare('INSERT INTO selected_courses (cid) VALUES (?)');
$stmt->bindParam(1, $cid);
foreach ($_POST['courses'] as $cid) {
$stmt->execute();
}

Categories