I have 2 textbox array,
questions & correct answer...
the problem is , i cannot save it to the the database
questions should be saved to "test" field in database
and correct answer should be saved to "test2" field...
code for the textbox
echo "<label for='textfield[]' align='left'> Question </label>";
echo "<br/>";
echo "<input type='text' name='textfield[]'>";
echo "<br/>";
echo "<label for='textfield2[]' align='left'> Correct Answer </label>";
echo "<br/>";
echo "<input type='text' name='textfield2[]'>";
echo "<br/>";
code for inserting values in database
$sql = array();
foreach($_POST['textfield'] as $textfield){
foreach($_POST['textfield2'] as $textfield2){
$sql[] = "INSERT INTO practice (test,test2) VALUES ('{$textfield}','{$textfield2}')";
}
}
foreach($sql as $query){
mysqli_query($con,$query);
}
}
You can insert like this,
<?php
$post_count = count($_POST['textfield']);
$post1 = array();
$post2 = array();
$post1 = $_POST['textfield'];
$post2 = $_POST['textfield2'];
for ($i = 0; $i <= $post_count; $i++) {
$sql[] = "INSERT INTO practice (test,test2) VALUES ('".$post1[$i]."','".$post2[$i]."')";
}
foreach ($sql as $query) {
mysqli_query($con, $query);
}
?>
Related
hi friends i'm creating a php page to import the data from a csv file into sql database..
here database table and number of fields are specified by user itself..
if user specifies 4 fields, then it is created using a for loop as follows..
<?php
include('connect.php');
$name = $_POST['table_name'];
//echo $name;
$create_tab = "CREATE TABLE $name(id varchar(15) PRIMARY KEY)";
if(mysql_query($create_tab,$con))
{
echo "Table <b><i>$name</i></b> created successfully... <br/> <br/>Add columns...";
}
else {
die('Error1'.mysql_error());
}
$field = $_POST['number_of_fields'];
//echo $name.$field;
echo '<form id="form1" name="form1" method="post" action="update-table.php">';
echo "<p>
<label for='tablename'></label>
<input type='hidden' name='tablename' id='tablename' value='$name' size='5'/>
</p>";
echo "<p>
<label for='fields'></label>
<input type='hidden' name='fields' id='fields' value='$field' size='5'/>
</p>";
echo '<table border="1" cellpadding="5" cellspacing="5">';
for ( $i = 1; $i <= $field; $i ++) {
echo '<tr>';
echo '<td>';
echo "<p>
$i
</p>";
echo'</td>';
echo '<td>';
echo "<p>
<label for='textfield$i'></label>
<input type='text' name='field$i' id='textfield$i' />
</p>";
echo'</td>';
echo '<td>';
echo "
<select name='select$i' id='select$i'>
<option value='varchar(200)'>varchar</option>
<option value='int'>int</option>
<option value='float'>float</option>
<option value='date'>date</option>
</select>";
echo '</td>';
echo '</tr>';
}
echo '</table>';
?>
<p>File Location :
<input type="text" name="fileField" id="fileField" />
</p>
<br/>
<INPUT type="image" name="search" src="images/alter.gif" border="0" height="75" width=120">
</form>
then table create and alter as follows..
<?php
include('connect.php');
$field = $_POST[fields];
$name = $_POST[tablename];
for ( $i = 1; $i <= $field; $i++) {
//getting field names
$varname = ($txtfield . $i);
$$varname = $_POST[field.$i];
// echo $$varname;
$fi = $$varname;
//getting field types
$selname = ($selfield . $i);
$$selname = $_POST[select.$i];
$dt = $$varname;
$sql = "ALTER TABLE $name ADD $fi $dt";
if(mysql_query($sql,$con))
{
echo "Field <b><i>$fi</i></b> added successfully...<br/>";
}
else {
die('Error1'.mysql_error());
}
}
?>
as above database table and fields are crated...
i got the concept of inserting data using static variables as follows..
<?php
// data import
include('connect.php');
$field = $_POST['fileField']; //file directory
echo "<br/><br/>Import file path: ";
echo $field;
$file = $field;
$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
if($line_num==0) { continue; } //escape the header column
$arr = explode(",",$line);
$column1= $arr[0];
$column2= $arr[1];
// ' escape character
if (strpos($column2, "'") == FALSE)
{
$column21 = $column2;
}
else{
$column21 = str_replace ("'", "\'", $column2);
}
$column3= $arr[2];
$column4= $arr[3];
//print data from csv
echo "<table border='1' width='800' cellpadding='5' cellspacing='2'>";
echo "<tr>";
echo "<td width='8'>";
echo $column1;
echo "</td>";
echo "<td width='100'>";
echo $column21;
echo "</td>";
echo "<td width='5'>";
echo $column3;
echo "</td>";
echo "<td width='5'>";
echo $column4;
echo "</td>";
echo "</tr>";
echo "</table>";
$import="INSERT into $name (id,name,year1,year2) values(
'$column1','$column21','$column3','$column4')";
mysql_query($import) or die(mysql_error());
}
?>
now, my question is how can i make this insert statement dynamic as such it creates field names and values dynamically inside insert query from the data obtained from for loop in table create and alter query???
If I understand your question correctly, it sounds like you want to combine your inserts into one query (which is very smart performance wise). SQL allows you to insert multiple rows at once like so:
INSERT INTO table (id, first, last) VALUES(NULL, 'Ryan', 'Silvers'),(NULL, 'Oscar', 'Smith'),(NULL, 'Jessica', 'Owens')
So by using creating an array of VALUES and using implode to join them you can make one query:
//Create rows
foreach($rows as $row) {
$queryRows[] = "(NULL, '".$row['first']."', '".$row['last']."')";
}
//Create query
$query = 'INSERT INTO table (id, first, last) VALUES'.implode(',', $queryRows);
Now that I understand your real question, I can give you a basic overview of what you need to do to achieve this. You need to create a form that allows a user to enter data that will be inserted into the table.
<form method="post" action="process.php">
<input name="field1" />
<!-- and more -->
</form>
Then you need to write a PHP script to process the form submission and insert the data into MySQL:
<?php
//Check form submission and validate entries, then...
$stmt = $pdo->prepare('INSERT INTO table (field1) VALUES(:field1)');
$stmt->execute(array(':field1', $_POST['field1']));
?>
Then you need to write a PHP script to process the form submission and insert the data into MySQL:
function insert($tablet,$datad)
{
if(empty($tablet)) { return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$query1 = "select * from user";
$result1 = mysql_query($query1);
$numcolumn = mysql_num_fields($result1);
$addd = "";
$count = 0;
for ( $i = 1; $i < $numcolumn; $i++ )
{
$columnnames = mysql_field_name($result1, $i);
if(($numcolumn-1) == $i)
{
$addd .= $columnnames;
$data .= "'".$datad[$count]."'";
}
else
{
$addd .= $columnnames.",";
$data .= "'".$datad[$count]."',";
}
$count++;
}
$ins = "INSERT INTO ".$tablet."(".$addd.")"."VALUES(".$data.")";
mysql_query($ins);
header('Location: index.php');
exit;
}
I have a "racing" website where I am recording racers results, but I am trying to enter their results in all at once. shown below is the code
Your problem is that you believe when you have multiple <input name="" /> you think that creates a array $_POST[], that is not true...
while ($row = mysql_fetch_assoc($result))
{
$reID = $row['reID'];
$racerID = $row['racerID'];
echo "<tr>";
echo "<td>$reID<input type='hidden' name='reID' value='$reID'>";
echo "<td>$racerID<input type='hidden' name='racerID' value='$racerID'>";
echo"<td><input type='text' name='rank'>";
echo"<td><input type='text' name='timetaken'>";
}
you are over writing the reID, racerID, rank, and time taken every time it is printed out... by default it takes the last one.
what you could do to solve this is:
$count = 0;
while ($row = mysql_fetch_assoc($result))
{
$count++;
$reID = $row['reID'];
$racerID = $row['racerID'];
echo "<tr>";
echo "<td>$reID<input type='hidden' name='reID$count' value='$reID'>";
echo "<td>$racerID<input type='hidden' name='racerID$count' value='$racerID'>";
echo"<td><input type='text' name='rank$count'>";
echo"<td><input type='text' name='timetaken$count'>";
}
echo "<input type='hidden' name='count' value='$count' />";
That way each value is unique...
Then instead of this:
$rank=$_POST['rank'];
$timetaken=$_POST['timetaken'];
$reID=$_POST['reID'];
$racerID=$_POST['racerID'];
$count_racerID= count($_POST['racerID']);
do this
$count = $_POST['count'];
for($i=1; $i<=$count; $i++){
$rank[] = $_POST['rank'.$i];
$timetaken[] = $_POST['timetaken'.$i];
$reID[] = $_POST['reID'.$i];
$racerID[] = $_POST['racerID'.$i];
}
$count_racerID = $count;
now you have arrays!
For your SQL statement...
$sql = mysql_query("INSERT INTO RaceResults (rank, timetaken, reID, racerID) VALUES ('$rank', '$timetaken', '$reID', '$racerID')");
should be
$sql = mysql_query("INSERT INTO RaceResults (rank, timetaken, reID, racerID) VALUES ('$_rank', '$_timetaken', '$_reID', '$_racerID')");
The final product should be something like this:
The input form:
$reID = $_GET['reID'];
$result = mysql_query("SELECT * FROM RaceEventRacer WHERE reID = $reID");
$count = 0;
while ($row = mysql_fetch_assoc($result))
{
$count++;
$reID = $row['reID'];
$racerID = $row['racerID'];
echo "<tr>";
echo "<td>$reID<input type='hidden' name='reID$count' value='$reID'>";
echo "<td>$racerID<input type='hidden' name='racerID$count' value='$racerID'>";
echo"<td><input type='text' name='rank$count'>";
echo"<td><input type='text' name='timetaken$count'>";
}
echo "<input type='hidden' name='count' value='$count' />";
and the SQL should be:
$count = $_POST['count'];
for($i=1; $i<=$count; $i++){
$rank[] = $_POST['rank'.$i];
$timetaken[] = $_POST['timetaken'.$i];
$reID[] = $_POST['reID'.$i];
$racerID[] = $_POST['racerID'.$i];
}
$count_racerID = $count;
for($i=0;$i<$count_racerID;$i++){
$_rank= mysql_escape_string($rank[$i]);
$_timetaken= mysql_escape_string($timetaken[$i]);
$_reID= mysql_escape_string($reID[$i]);
$_racerID= mysql_escape_string($racerID[$i]);
$sql = mysql_query("INSERT INTO RaceResults (rank, timetaken, reID, racerID) VALUES ('$_rank', '$_timetaken', '$_reID', '$_racerID')");
$result = mysql_query($sql);
}
I'm having problems to find how to create an hyperlink in a table column result and then, on click, open another page with all fields (textboxes) filled. Imagine when a click an ID, i do a select * from table where column_id = ID... Is there a way to do it?
Thanks.
Best regards
I'm not completely sure what you are asking, but this may help you a bit.
First make a Javascript.
<script type="text/JavaScript">
function selectID() {
var ID = document.getElementById("ID").value;
document.location.href ="yoursite.php?ID="+ID;
}
</script>
Then connect to your database to query the table for a link ID (or more) for example by changing the variable $value.
<?php
//Connect to database
mysql_connect("host", "user", "pass");
mysql_select_db("db_name");
$value = 'something';
$ID = $_GET['ID'];
if (!$ID) {
$ID = 0;
}
if ($ID == 0) {
$query = "SELECT * FROM table WHERE `column_1` = '$value'";
$result = mysql_query($query);
echo "<table>";
while($myrow = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>";
echo "ID";
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
elseif ($ID > 0) {
$query2 = "SELECT * FROM table WHERE `column_id` = '$ID'";
$result2 = mysql_query($query2);
while($myrow2 = mysql_fetch_array($result2)) {
$value1 = $myrow2['column_1'];
$value2 = $myrow2['column_2'];
}
echo "<form type=\"GET\" action=\"$PHP_SELF\">";
echo "<input type=\"text\" id=\"ID\" name=\"ID\" value=\"$ID\"><br>";
echo "<input type=\"text\" id=\"value1\" name=\"value1\" value=\"$value1\"><br>";
echo "<input type=\"text\" id=\"value2\" name=\"value2\" value=\"$value2\"><br>";
echo "<input type=\"hidden\" id=\"search\" name=\"search\" value=\"searching\">";
echo "<input type=\"submit\" id=\"submitbutton\" name=\"submitbutton\" value=\" Search \">";
echo "</form>";
}
?>
I got a php form to update MySQL tables. The fetch works perfectly but the updates are not working. This is my form code :
<?php
$sql= "SELECT client.resID AS resID, client.resName AS resName FROM client WHERE client.resID =".$_GET["resID"];
$rs = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$sqlM= "SELECT menu.id AS mid, menu.name AS mname FROM menu WHERE menu.resID =".$_GET["resID"];
$rsM = mysql_query($sqlM) or die($sqlM."<br/><br/>".mysql_error());
$sqlF= "SELECT facilities.id AS fid, facilities.name AS fname FROM facilities WHERE facilities.resID =".$_GET["resID"];
$rsF = mysql_query($sqlF) or die($sqlF."<br/><br/>".mysql_error());
$sqlS= "SELECT services.id AS sid, services.name AS sname FROM services WHERE services.resID =".$_GET["resID"];
$rsS = mysql_query($sqlS) or die($sqlS."<br/><br/>".mysql_error());
// $names array now contains all names
$i = 0;
echo '<table width="50%">';
echo '<tr>';
echo '<td>ID</td>';
echo '<td>Name</td>';
echo '<td>Edit</td>';
echo '</tr>';
echo "<form name='form_update' method='post' action='client_admin_post.php'>\n";
while ($fm = mysql_fetch_array($rsM)) { // loop as long as there are more results
$mnames[] = $fm['mname'];
$mid[] = $fm['mid']; // push to the array
echo '<tr>';
echo "<td>Menu :</td>";
echo "<td><input type='text' size='40' name='mname' value='{$fm['mname']}' /></td>";
echo "<td>{$fm['id']}<input type='hidden' name='mid' value='{$fm['mid']}' /></td>";
echo '</tr>';
++$i;
print_r($mnames);
}
while ($ff = mysql_fetch_array($rsF)) { // loop as long as there are more results
$fnames[] = $ff['fname'];
$fid[] = $ff['fid']; // push to the array
echo '<tr>';
echo "<td>Facilities :</td>";
echo "<td><input type='text' size='40' name='fname' value='{$ff['fname']}' /></td>";
echo "<td>{$ff['id']}<input type='hidden' name='fid' value='{$ff['fid']}' /></td>";
echo '</tr>';
++$i;
}
while ($fs = mysql_fetch_array($rsS)) { // loop as long as there are more results
$snames[] = $fs['sname'];
$sid[] = $fs['sid']; // push to the array
echo '<tr>';
echo "<td>Services :</td>";
echo "<td><input type='text' size='40' name='sname' value='{$fs['sname']}' /></td>";
echo "<td>{$fs['id']}<input type='hidden' name='sid' value='{$fs['sid']}' /></td>";
echo '</tr>';
++$i;
}
echo'<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>';
?>
This is my post code :
$size = count($_POST['mname']);
$i = 0;
while ($i < $size) {
$mname= $_POST['mname'][$i];
$mid = $_POST['mid'][$i];
$query = "UPDATE menu SET name = '$mname' WHERE id = '$mid' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
echo "$mname<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
$size = count($_POST['fname']);
$i = 0;
while ($i < $size) {
$fname= $_POST['fname'][$i];
$fid = $_POST['fid'][$i];
$query1 = "UPDATE facilities SET name = '$fname' WHERE id = '$fid' LIMIT 1";
mysql_query($query1) or die ("Error in query: $query1");
echo "$fname<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
$size = count($_POST['sname']);
$i = 0;
while ($i < $size) {
$sname= $_POST['sname'][$i];
$sid = $_POST['sid'][$i];
$query3 = "UPDATE services SET name = '$sname' WHERE id = '$sid' LIMIT 1";
mysql_query($query3) or die ("Error in query: $query3");
echo "$sname<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
I got 'updated' status in post page but nothing is updated in MySQL table. How to solve this problem? Really appreciate your help :D
You're creating multiple inputs with the same name, such as "fname," but you're trying to access them as if they were an array. Rename the fields like the following:
echo "<td><input type='text' size='40' name='mname[]' value='name' /></td>";
too long question but if you but by update status in post page you mean to say it echoed update if i am right it will echo update since you are checking it in while and the condition is true. But have you echoed the posted values in post page check whether you are getting the value proceed this way to find where are you having problems before asking here long questions.
you can use transacrions in mysql if you want all the queries should be executed otherwise none.
Your post page says updated because at the end of your queries you just echo "Updated", there is no condition when it should be printed.
and your data is not updated as you are not specifying any connection variable for mysql_query("query",$conn)
i try to store the booking booths into database based on user selection, there are 10 check boxes for each booths and user can choose which day they want to reserve booths. For each check box has it own field in database, if user choose booth A01, D1 and D2, when he press reserve button, it will insert value into D1 and D2. But I dont know how to get the checked checkbox value to store in database
my booth interface
http://i.imgur.com/umYcI.gif
my table structure
http://i.imgur.com/vKh6R.gif
My coding
<?php
session_start();
if ( !isset($_SESSION['AUTHORIZED_USERNAME']) || empty($_SESSION['AUTHORIZED_USERNAME']) ) {
header("location:index.php");
}else{
$user=$_SESSION['AUTHORIZED_USERNAME'];
}
include('db.php');
if($_REQUEST){
$id = $_REQUEST['search_category_id'];
$query2 = mysql_query("SELECT filenameBig, filename, url FROM eventinfo where eventID ='$id'");
$row = mysql_fetch_array($query2, MYSQL_ASSOC);
if($id == -1)
{
echo "<style type='text/css'>#btn_submit{visibility:hidden}</style>";
}
else{
/*echo "<a href='{$row['url']}'>Click me!</a>";*/
echo "<p><br><img src='{$row['filename']}' alt='' /></p>";
echo "<p></p>";
echo "<p align='right'><a href='$row[filenameBig]' target='_blank'>Click to view large image</a></p>";
echo "<hr size='1'>";
echo "<div style='padding-left:4px;' align='left'><strong>Booths Listing</strong>";
echo "<p></p>";
$query = "select boothAlias, totalDay from booths, eventinfo where booths.eventID=eventinfo.eventID && booths.eventID = ".$id."";
$_SESSION['EVENT_ID']=$id;
$result = mysql_query($query);
$result2= mysql_query($query);
echo "<table border='0' style='width:400px;table-layout:fixed' >";
$rows2 = mysql_fetch_array($result);
$Day=$rows2['totalDay'];
echo "<table>";
for ($day = 0; $day <= $Day; ++$day) {
if($day==0){
echo "<th>Booth</th>";
}else{
echo "<th>D".$day."</th>";
}
}
while($rows = mysql_fetch_array($result2)){
$boothAlias=$rows['boothAlias'];
$totalDay=$rows['totalDay'];
echo "<tr><td>$boothAlias</td>";
for ($day2 = 1; $day2 <= $totalDay; ++$day2) {
echo "<td><input name='day2[]' type='checkbox' value='$day2' /></td>";
}
echo "</tr>";
}
echo "</table>";
}
}
?>
I think that SET type would be good solution for this.
http://dev.mysql.com/doc/refman/5.0/en/set.html