PHP dynamic form will not INSERT into mySql - php

I'm working on a PHP dynamic form based on the tutorial found here:
http://blog.calendarscripts.info/dynamically-adding-input-form-fields-with-jquery/
Here is the table layout:
ID | depratecat | MinBalance | InterestRate | APY | suborder
inputted rows
ID is auto-increment.
The form fields for depratecat are visible in my code only for testing; normally the user would not be able to change this value. The value of depratecat would come from a POST value from a previous page and should be the same for all rows inputted or edited in this instance. For testing I'm declaring the value as 14.
My test page is here:
http://www.bentleg.com/fcsbadmin/dynamictest4.php
The problems:
The "Add row" script function does not work and the code won't insert new data thru form; nothing happens. No errors are shown in the Chrome console
Editing or deleting pre-existing rows seems to work.
Below is my complete test code minus the connection, Some print_r added to show the array.:
<?php
error_reporting(E_ALL);
// Connect to the DB
$link = myconnection stuff
$new_depratecat='14'; //for testing
// store in the DB
if(!empty($_POST['ok'])) {
//first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM tblRates_balance WHERE id=$id";
$link->query($sql);
}
}
// now, to edit the existing data, we have to select all the records in a variable.
$sql="SELECT * FROM tblRates_balance WHERE depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
// now edit them
while($rates = mysqli_fetch_array($result)) {
// remember how we constructed the field names above? This was with the idea to access the values easy now
$sql = "UPDATE tblRates_balance SET
MinBalance='".$_POST['MinBalance'.$rates['id']]."',
InterestRate='".$_POST['InterestRate'.$rates['id']]."',
APY='".$_POST['APY'.$rates['id']]."',
suborder='".$_POST['suborder'.$rates['id']]."'
WHERE id='$rates[id]'";
$link->query($sql);
}
// (feel free to optimize this so query is executed only when a rate is actually changed)
// adding new
if($_POST['add_MinBalance']!= "") {
//echo ("OKAY");
$sql = "INSERT INTO tblRates_balance (depratecat, MinBalance, InterestRate, APY, suborder) VALUES ('$new_depratecat','".$_POST['add_MinBalance']."', '".$_POST['add_InterestRate']."', '".$_POST['add_APY']."','".$_POST['add_suborder']."' );";
$link->query($sql);
}
}
// select existing rates here
$sql="SELECT * FROM tblRates_balance where depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
?>
<html>
<head>
<title>Example of dynamically adding row and inserting into mySql with jQuery</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<h1>Example of dynamically adding row and inserting into mySql with jQuery </h1>
<form method="POST" id="newrate">
<div id="itemRows">
Minimum Balance: <input type="text" name="add_MinBalance" size="30" />
Interest Rate: <input type="text" name="add_InterestRate" />
APY: <input type="text" name="add_APY" />
Order: <input type="text" name="add_suborder" size="2"/>
<< Add data and click on "Save Changes" to insert into db. <br>
You can add a new row and make changes to existing rows all at one time and click on "Save Changes."
New entry row will appear above after saving.
<?php
// Next section does updating. let's assume you have the rate data from the DB in variable called $rates
while($rates = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$rates['id']?>">
<?php //echo $rates['id']; ?>
Minimum Balance: <input type="text" name="MinBalance<?=$rates['id']?>" value="<?=$rates['MinBalance']?>" />
Interest Rate: <input type="text" name="InterestRate<?=$rates['id']?>" value="<?=$rates['InterestRate']?>" />
APY: <input type="text" name="APY<?=$rates['id']?>" value="<?=$rates['APY']?>" />
Order: <input type="text" name="suborder<?=$rates['id']?>" value="<?=$rates['suborder']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$rates['id']?>"> Mark to delete</p>
<?php endwhile;?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script language="Javascript" type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Minimum Balance:<input type="text" name="add_MinBalance[]" value="'+frm['add_MinBalance[]'].value+'">Interest Rate:<input type="text" name="add_InterestRate[]" value="'+ frm['add_InterestRate[]'].value +'">APY:<input type="text" name="add_APY[]" value="'+frm['add_APY[]'].value+'">Order:<input type="text" name="add_suborder[]"value="'+ frm['add_suborder[]'].value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+')(this);"></p>';
jQuery('#itemRows').append(row);
frm['add_MinBalance[]'].value = '';
frm['add_InterestRate[]'].value = '';
frm['add_APY[]'].value = '';
frm['add_suborder[]'].value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
//}
</script>
</body>
</html>

The inputs in the initial form have names add_depratecat, add_MinBalance, add_InterestRate, add_APY, and add_suborder. When you add new rows, they have the same names, but with [] appended. So the original row creates single inputs, the added rows create array inputs, but they have the same names, and they conflict.
You should use the array form for the original inputs as well:
<form method="POST" id="newrate">
<div id="itemRows">
Dep_rate_cat:<input type="text" name="add_depratecat[]" size="30"/>
Minimum Balance: <input type="text" name="add_MinBalance[]" size="30" />
Interest Rate: <input type="text" name="add_InterestRate[]" />
APY: <input type="text" name="add_APY[]" />
Order: <input type="text" name="add_suborder[]" size="2"/>
so that they're consistent with the added rows.

Initially you are not adding [] in the form fields,
change <input type="text" name="add_depratecat" size="30"> to <input type="text" name="add_depratecat[]" size="30">, do the same for other fields as well.
And in foreach where you are inserting data to database use array $depratecat[] instead of string $depratecat
if(isset($_POST['add_depratecat'])) {
$depratecat = $_POST['add_depratecat']; ........
For debugging purpose write echo '<pre>'; print_r($_POST); OR var_dump($_POST); Instead of
echo '<pre>',print_r($_POST,true),'</pre>';.

Related

Form Data Gets Inserted Into MySQL Table But Still Server Throws Error

I want to insert some values into my book table and I created a PHP page with HTML form inside it. The problem is my values gets inserted but it throws a primary key error on the webpage. The code is as below.
<!DOCTYPE html>
<html>
<head>
<title>New Books</title>
</head>
<body>
<?php
if (isset($_POST['submit'])) {
$server="localhost";
$username="root";
$password="";
$db="library";
$conn= new mysqli($server,$username,$password,$db);
if ($conn->connect_error) {
echo "Server Error Occured Please Try Again Later";
}
$bid=$_POST['bid'];
$bname=$_POST['bname'];
$baut=$_POST['baut'];
$bc=$_POST['bc'];
$blf=$_POST['blf'];
$bs=$_POST['bs'];
$sql="insert into books(BOOK_ID,BOOK_NAME,BOOK_AUTHOR,BOOK_CATEGORY,BOOK_LOST_FINE, BOOK_STATUS) values('$bid','$bname','$baut','$bc','$blf','$bs')";
$result=$conn->query($sql);
if ($conn->query($sql)===TRUE) {
echo "New Book Added Successfully";
}
else{
echo "Please Recheck The Values Entered" . $conn->error;
$secondsWait = 5;
header("Refresh:$secondsWait");
}
}
?>
<div class="header">
Lowa State University
<div class="header-right">
<a class="active" href="#">Main Page</a>
Due Fines
Contact Us
Profile
</div>
</div>
<form action="" method="post">
<input type="text" name="bid" placeholder="BOOK ID"><br><br>
<input type="text" name="bname" placeholder="BOOK NAME"><br><br>
<input type="text" name="baut" placeholder="BOOK AUTHOR"><br><br>
<input type="text" name="bc" placeholder="BOOK CATEGORY"><br><br>
<input type="number" name="blf" placeholder="BOOK LOST FINE"><br><br>
<input type="text" name="bs" placeholder="BOOK STATUS"><br><br>
<input type="submit" name="submit" value="Add Book"><br><br>
<input type="reset" name="reset" value="Clear Fields">
</form>
</body>
</html>
SAMPLE VALUES IN FORM
Now if I press the add button this error shows up:
Error Image:
but the values are already entered into the SQL table.
When you add any field as primary key that mean it must have unique record, no duplication allowed. you trying to add duplicate(same record) in same table.
You should add BOOK_ID as primary key + auto increment in database and when you insert new record, you don't need to add BOOK_ID manually at code. i automatically incremented from previous record and added automatically.
Just do like this
$sql="insert into
books(BOOK_NAME,BOOK_AUTHOR,BOOK_CATEGORY,BOOK_LOST_FINE,
BOOK_STATUS) values('$bname','$baut','$bc','$blf','$bs')";
and remove following line $result=$conn->query($sql);
Note [add BOOK_ID AS PRIMARY KEY + AUTO INCREMENT in Table]
Just like hingu Devang and Bira mentioned, make your ID column Auto_Increment and do not manually place a value there because it will automatically assign a value.
As for your issue that the query is being executed twice, try removing the line:
$result=$conn->query($sql);
Because you already have a query which is:
if($conn->query($sql)===TRUE)

Editing data in multiple columns from front-end

I have a table in the database, I can edit a column of particular row at a time. but, i want to edit multiple columns of a single row at a time with an option of edit and then save it to the database ,we can do it from back-end by editing in the database itself. But, i want to do it from front-end .Now i am able to display the data in the table. I am new to coding , so can anyone help me where to start for this particular task of editing multiple columns at the same time.
Here is the code for displaying the data..
<?php
include('db.php');
include 'header.php';
include 'gobacktomenu.php';
$TND_ID = $_GET['TND_ID'];
$sql = "SELECT * FROM new_tnds WHERE TND_ID = ('".$TND_ID."')";
$result = $link->query($sql);
echo "<div style='overflow-x:auto;'><table border = '1'><font size = '2' face='verdana'>
<th>TND ID</th><th>Site name S1</th><th>Site name S2</th><th>Call sign S1</th><th>Idea ID S1</th><th>Call sign S2</th><th>Idea ID S2</th><th>Site to integrate</th><th>True azimuth (°) S1</th><th>True azimuth (°) S2</th><th>Pathlength (km)</th><th>TR Antenna diameter (m)</th><th>TR Antenna height (m) S1</th><th>TR Antenna height (m) S2</th><th>Channel ID S1</th><th>Channel ID S2</th><th>Design frequency S1</th><th>Design frequency S2</th><th>Polarization</th><th>Radio model</th><th>TX power (dBm)</th><th>Receive signal (dBm)</th><th>Planning Remarks</th><th>Projects Remarks Uploaded by</th><th>O & M Remarks Uploaded by</th><th>Planning Remarks Uploaded by</th><th>TXN NOC Remarks Uploaded by</th></tr>";
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
echo "<tr><td>".$row["TND_ID"]."</td><td>".$row["Site_name_S1"]."</td><td>".$row["Site_name_S2"]."</td><td>".$row["Call_sign_S1"]."</td><td>".$row["Idea_ID_S1"]."</td><td>".$row["Call_sign_S2"]."</td><td>".$row["Idea_ID_S2"]."</td><td>".$row["Site_to_integrate"]."</td><td>".$row["True_azimuth_S1"]."</td><td>".$row["True_azimuth_S2"]."</td><td>".$row["Path_length_(km)"]."</td><td>".$row["TR_Antenna_diameter_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S2"]."</td><td>".$row["#1_Channel_ID_S1"]."</td><td>".$row["#1_Channel_ID_S2"]."</td><td>".$row["#1_Design_frequency_S1"]."</td><td>".$row["#1_Design_frequency_S2"]."</td><td>".$row["Polarization"]."</td><td>".$row["Radio_model_S1"]."</td><td>".$row["TX_power_(dBm)_S1"]."</td><td>".$row["Receive_signal_(dBm)_S1"]."</td><td>".$row["Planning_Remarks"]."</td><td>".$row["Projects_remarksupdated_user_name"]."</td><td>".$row["O_M_remarksupdated_user_name"]."</td><td>".$row["Planning_remarksupdated_user_name"]."</td><td>".$row["txn_noc_remarksupdated_user_name"]."</td></tr>";
}
echo "</table></div>";
$link->close();
?>
you can use this structure ,this can be used for editing 2 tables and multiple columns table a has columns (aid,a1,a2) table b has columns (bid,b1,b2) i know code looks little rough but just wrote it in 5 min to give you an idea
<?php
//this only executes when button is clicked
if (isset($_POST["submit"] && $_POST["submit"]!=""){
$counta=$_POST["aid"];
//loops through the posts inside here do your query with the set command
//like "update a set a1='$a1',a2='$a2" where aid ='$_POST["aid'][$i]"
for($i=0;$i<$count;$i++){
$a1[$i]=$_POST["a1"][$i];
$a2[$i]=$_POST["a2"][$i];
//your query here
}
$countb=$_POST["bid"];
//loops through the posts inside here do your query with the set command
//like "update b set b1='$b1',b2='$b2" where aid ='$_POST["bid'][$i]"
for($i=0;$i<$count;$i++){
$a1[$i]=$_POST["a1"][$i];
$a2[$i]=$_POST["a2"][$i];
}
//now the part before the button gets clicked
//do your query to select data from database
?>
<html>
<body>
//creating loop inside html
<?php
$a=0;
while($rowa = mysql_fetch_assoc($resulta){
?>
//getting the input data
<input type="checkbox" name="aid[]" value="<?php echo $row["aid"]; ?>>
<label>a1</label>
<input type="text" name="a1[]" value="<?php echo $row["a1"]; ?>>
<label>a2</label>
<input type="text" name="a2[]" value="<?php echo $row["a2"]; ?>>
//ending the loop
<?php
$a++;
}
//b works the same as a
$b=0;
while($rowb = mysql_fetch_assoc($resultb){
?>
<input type="checkbox" name="bid[]" value="<?php echo $row["bid"]; ?>>
<label>b1</label>
<input type="text" name="b1[]" value="<?php echo $row["b1"]; ?>>
<label>b2</label>
<input type="text" name="b2[]" value="<?php echo $row["b2"]; ?>>
<?php
$b++;
}
?>
<input type="submit" name="submit" value="submit">
</body>
</html>
You need use form instead of table while editing and pass the fetched values on input of form and write update query on form submit.
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
}
if(isset($_POST['submit']))
{
$query = "update details set Site_name_S1='$_POST['submit']',Site_name_S2='$_POST['Site_name_S2']',Call_sign_S1='$_POST['Call_sign_S1']',Idea_ID_S1='$_POST['Idea_ID_S1'] where TND_ID=$_POST['TND_ID']";
$res = mysql_query($query);
}
<form method="post">
<input type="text" name="id" value="<?php echo $row['TND_ID'] ;?>" >
<input type="text" name="Site_name_S1" value="<?php echo $row['Site_name_S1'] ;?>" >
<input type="text" name="Site_name_S2" value="<?php echo $row['Site_name_S2'] ;?>" >
<input type="text" name="Call_sign_S1" value="<?php echo $row['Call_sign_S1'] ;?>" >
<input type="text" name="Idea_ID_S1" value="<?php echo $row['Idea_ID_S1'] ;?>" >
<input type="submit" name="submit">
</form>
Just check the quotes while writing update query.
You can use Ajax
Just a fragment of code:
.............
<td><input type="text" row_id=".$some_row_num_from_table."
col-name=".$some_col_name_from_table." disabled class="some-val" value=".$some_from_base."></td>
.............
than little Ajax
$('.some-val').dblclick(function() {
$(this).attr('disabled', false);
});
$('.some-val').blur(function() {
$(this).attr('disabled', true);
var send_data = { 'row_id':$(this).attr('row_id'),
'col-name':$(this).attr('col-name'),
'myval':$(this).val()
};
$.ajax({
url:'your_url.php',
data:send_data,
method: 'post',
success: function(data){...}
});
});
your_url.php
if(isset($_POST['row_id'])){
$sql = "UPDATE mytablename SET `".$_POST['col-name']."` = ".$_POST['myval']." WHERE `row_id` = ".$_POST['row_id'];
$link->query($sql); // it s bad query without protect of sql injection JUST DEMO
}

checkbox value to mysql/php

im triyng to figure out a problem for days and have some progress but im stuck with some checkbox page.
So the "project" is some kind of "online car stand" and im stuck in the insert car part.
I got the html and php for insert a car into the sql table.
Then after the car i have a link to insert extras of the car, like abs,cruise control, gps ...etc...
The Html is something like this:
<?php
include "verifica.php";
?>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title> Stand Automovel
</title>
</head>
<body>
<form action="extras.php" method="POST">
<P class="style2"style2"> Extras:
<div class="style2">
<input type="checkbox" name="chk" value="1">GPS<br>
<input type="checkbox" name="chk" value="2">ABS<br>
<input type="checkbox" name="chk" value="3">Computador De Bordo<br>
<input type="checkbox" name="chk" value="4">Ar Condicionado<br>
</div>
<P> </P>
<P><INPUT TYPE=submit VALUE="Submeter"> <INPUT TYPE=reset VALUE="Limpar"> </P>
<P> </P>
</form>
</body>
The php page code is this one:
<html>
<head>
<meta charset="UTF-8">
<title>Inserir Automoveis</title>
</head>
<body>
<?php
include "connect.php";
$sql = "INSERT INTO extra (extra.id_carro,extra.id_lista_extra) SELECT carro.id_extras , ? FROM carro,lista_extra,extra ORDER BY carro.id_carro DESC LIMIT 1";
if($teste= $mysqli->prepare($sql)) {
$teste->bind_param("s",$_REQUEST["extra.id_lista_extra"]);
$teste->execute();
if ($teste>affected_rows == -1) {
echo $print;
echo "<p>". $mysqli->error. "</p>";
}
else {
echo "<sp>Carro inserido com sucesso!</p>";
}
}
?>
The goal with that $sql is to get the last id from last car inserted on row cars and add 1 extra to him passed by the check box.
i have tried just with 1 box because i read that if a checkbox was unchecked pass "null"argument.
I tried already with diferent aproaches. My final goal is create a for cicle that creates the number of rows in table extra for each number of extra checked in my checkbox.
(i tried something like this but with no sucess)
$checkbox1 = $_POST['chk'];
if($_POST["Submit"]=="Submit"){
for ($i=0;$i<sizeof ($checkbox1)$i++){
$sql = "INSERT INTO extra (id_lista_extra) values('".$checkbox1[$i]."')";
mysql_query($sql) or die(mysql_error());
}
}
i got some php errors on that $i .
If someone can give me a hint i would appreciate.
Thanks
Here is an example all you would have to do is change the names inside these $_POST variables as well as change your HTML checkbox names to have a [] after them. e.g
<input type="checkbox" name="chk[]" value="1">GPS<br>
<input type="checkbox" name="chk[]" value="2">ABS<br>
$cat_array = array();
if(isset($_POST['chk'])){
if(is_array($_POST['chk'])) {
foreach($_POST['chk'] as $value){
array_push($cat_array, $value);
}
}else{
$value = $_POST['chk'];
array_push($cat_array, $value);
}
}
Now all these values are in an ARRAY. Do as you please with them, loop through them, call them by there indexes, etc..

Using MySQL random row in a select statement afterwards

I have a data base 'School'. It has only one table - 'Words'. There are word_id, word_name, word_description in it. I want to pull a random description and display it on a page. Then I want to input a word and see if the word has the same description as the random one that was pulled. What am I doing wrong? Here is the code -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Изпит</title>
</head>
<body>
<?php
$connection = mysqli_connect('localhost', 'root', '', 'school');
if(!$connection){
echo 'NOT OK';
exit;
}
if(isset($_POST['submit_description'])){
$q = mysqli_query($connection, ' SELECT word_description
FROM words ORDER BY rand() LIMIT 1
');
$row=mysqli_fetch_assoc($q);
if($row){
$_POST['word_description'] = $row['word_description'];
echo $_POST['word_description'];
}
}
if(isset($_POST['submit_word'])){
$word_name = $_POST['word_name'];
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
$result=mysqli_query($connection, $q2);
$count=mysqli_num_rows($result);
if($count==1){
echo 'Позна ве.';
}else{
echo 'Не позна ве.';
}
}
?>
<br><br><br>
<form method="POST">
<input type="submit" name="submit_description" value="Искай описание.">
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
</form>
<form method="POST">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
</body>
</html>
I think you have some typos.
This line of code here:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
Should be like this:
$q2="SELECT * FROM words WHERE word_name='".$word_name."' and word_description='".$_POST['word_description']."'";
1) There is a typo in $_POST['word_description'] in your query:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
2) Also, I would recommend using the word_id instead of the word description to make the verification... you would need to write it in a <input name="word_id" type="hidden" value="..." /> in your form to pass it along.
What would be even better, to prevent people from knowing the answer by looking at the code (in case they would know what word matches what id), you could encode the value in the hidden field to be md5($word_id.$word_name) and then in your query you check "WHERE MD5(CONCAT(word_id, word_name))='".$_POST['word_md5']."'" (assuming your hidden input is now called "word_md5).
EDIT:
After looking at the HTML I see what your problem is:
<form method="POST">
<input type="submit" name="submit_description" value="Искай описание.">
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
</form>
<form method="POST">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
This should all be in the same <form> element:
<form method="POST">
The word description is: <?php echo $_POST['word_description']; ?>
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
When the form is submitted, the $_POST array should contain the word_description AND the word_name submitted.
EDIT 2:
If you wish to use the id, you would have to first add it to your SELECT query:
$q = mysqli_query($connection, ' SELECT word_id, word_description
FROM words ORDER BY rand() LIMIT 1
');
Then you'd need to set it to some variable, and then later in your HTML:
<form method="POST">
The word description is: <?php echo $_POST['word_description']; ?>
<input type="hidden" name="word_id" value="<?php echo $word_id?>">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
Your second SQL query should then look like:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_id='".$_POST['word_id']."'";
Note: it is a bad practice to change the $_POST array in your code.
This array is populated by the request sent by the client and things can get confusing if you change the values there.
It is better to create another variable and set it to the value from the $_POST (example: $word_description = $_POST['word_description'];).
This way, you can still use array_key_exists('word_description', $_POST) to verify if the client actually sent something.

populating text fields from the sql using dropdown list Jquery

Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.

Categories