fill a select html with mysql table rows - mysql

I'm writting a web app, I'm doing a html form with javascript to validate the data, I'm using a servlet to insert the data in a DB, but I need, when the form load, fill a select in the html form with the rows of a table in a MySql DB, I think I have to make a query in a ResultSet and then fill the select in the html form with this info, and then use the HttpServletResponse, but I have no idea how to make this

Use PHP to access the database and then put it into the form. Something like this:
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM table_name WHERE id='$id'");
$info = mysql_fetch_array($result))
$name = $info['name'];
$email = $info['email'];
$anotherField = $info['another_field'];
In this, the info array has all of the database data in it of the id. But of course you would change the values and stuff. Change table_name to the table name, and if you are going to do something in the URL like ?id=373384 or something, then this will work. (I would assume you are doing it this way.) But, if it isn't 'id', just change WHERE id='$id' to what is in the database to identify a line.
$info['name']; would be the "name" column in your table. But, you can change 'name' and stuff to what you have in your database.
Here is the form code to pre-fill it with data:
<form>
<input type="text" name="name" value="<?php echo $name ?>" />
<input type="text" name="name" value="<?php echo $email ?>" />
<!--etc...-->
<input type="submit" value="Submit" />
</form>
You would need to change a lot of this, but I'm sure you get the point of it. :)
Note: This is not a simple copy+paste script. You will have to do a lot of charing because I don't know what your table values are and stuff.
If you have any questions, please do ask.

Related

HTML Form data from checkboxes within while loop

I have a really basic Date system on a site which displays the dates from the Database using a While loop, next to each date that is listed is a check box.
I would like the user to be able to select as many dates as they would like and click submit to remove these dates or edit these dates.
I am having trouble figuring out how I would get the data from multiple check-boxes using only one within the while loop which could be used multiple times?
Here is my current code:
<form action="" method="post">
<b>Current Dates:</b> <button type="submit" id="remove_dates" name="remove_dates" class="btn btn-danger btn-sm">Remove Selected</button>
<hr>
<div style="overflow-y: scroll;height:100px">
<?
$sqldate = "SELECT * FROM `foiu51r_calendar` ORDER BY date DESC";
$resultdate = $conn->query($sqldate);
if ($resultdate->num_rows > 0) {
// output data of each row
while($rowdate = $resultdate->fetch_assoc()) {
$date_id = $rowdate['date_id'];
$dates = $rowdate['date'];
?>
<input type="checkbox" id="date_id" name="date_id" value="<? echo $date_id; ?>"> <b><? echo date("d/m/Y", strtotime($dates)); ?></b><br>
<?
}
}
?>
</div>
</form>
if(isset($_POST['remove_dates'])){
$date_id = $_POST['date_id'];
}
I believe if you add this: [], to the name attribute, like this: <input type="checkbox" id="date_id" name="date_id[]" value="<? echo $date_id; ?>">. Then it will be handled as an array, which you can loop through with a foreach loop. and insert it into a database (or whatever you like).
Declare the name as an array, like as follows:
<input type="checkbox" id="date_id" name="date_id[]" value="<? echo $date_id; ?>">.
On submitting it will be handled as an array,
Then, you can loop the values of an array and for each element of an array use the id to remove the dates.

Getting PHP and SQL scripting to work properly

So, from what I have been learning for these past few weeks I believe I have sufficient knowledge on how to perform PHP, and SQL related queries to create a good and dynamic website that could support something like a forum. I've not been able to do that yet, and am having quite a bit of trouble with it as well. So far, I've made a PHP file, that was simply to see if I could use PHP well. It did not work out, and I've been getting plenty of errors, and I've been unable to fix them, whatsoever. And so, I'd like to come here to ask, if anyone out there could possibly analyze my code that I've written, and see what is wrong with it, if possible. Along with that, I'd like to know what would be the "Proper" way of
A. Connecting to SQL
B. Selecting Data
C. Displaying/Utilizing Data
And thank you, for reading and/or possibly replying to this.
Here, is the code I've written but have been unable to work.
<?php
include 'header.php';
include 'connect.php';
?>
<body>
<form>
Input First name:<br>
<input type="text" name="FN">
<br>
Input Last name:<br>
<input type="text" name="LN">
<br>
Input Email:<br>
<input type="text" name="Email">
<br>
<input type="submit" method="post">
<?php
if (isset($_POST['FN'], $_POST['LN'], $_POST['Email']))
$sql = 'INSERT INTO `info` ("USERID", "FN", "LN", "Email") VALUES (\'$_POST[FN]\', '$_POST["LN"]', '$_POST["Email"]')';
?>
</form>
<?php
$sql = "SELECT FN, LN, Email
FROM
info"
$result = "mysql_query($sql)"
while($row_list = mysql_fetch_assoc( $result )) {
ECHO <div>The Names are:</div><br>
ECHO $FN . "," . $LN . "," . $Email;
}
?>
</body>
</html>
Your PHP code is wrong in so many ways even in your query. What I did is clean your codes.
<?php
include 'header.php';
include 'connect.php';
?>
<body>
<form action="" method="POST">
Input First name:<br>
<input type="text" name="FN">
<br>
Input Last name:<br>
<input type="text" name="LN">
<br>
Input Email:<br>
<input type="text" name="Email">
<br>
<input type="submit" name="submit-btn" value="submit">
</form>
<?php
if (isset($_POST['submit-btn'])){
$sql = 'INSERT INTO info ( "FN", "LN", "Email") VALUES ('$_POST[FN]', '$_POST["LN"]', '$_POST["Email"]')';
if (mysql_query($sql)) {
echo "New record created successfully";
}
}
$sql = "SELECT FN, LN, Email FROM info";
$result = mysql_query($sql)
while($row_list = mysql_fetch_assoc( $result )) {
ECHO '<div>The Names are:</div><br>';
ECHO $FN . "," . $LN . "," . $Email;
}
?>
</body>
</html>
try to indent your code to make it more readable for yourself.
as already answered by user3814670, your insert query was wrong, with 4 elements (id,fn,ln,email) and only 3 data (fn,ln,email)
your query was't being executed also cleaned by user3814670 by adding the lines
if (mysql_query($sql)) {
echo "New record created successfully";
}
try to print your query to the screen and executing it in you database to see if your query fails or print the error to screen
mysql_error()
add this on top of your file after
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Here's how you display data from the database using while loop
while($row=mysql_fetch_array($result)) {
echo $row['FN'] . " " . $row['LN'] . " " . $row['Email'];
}

PHP getting data from HTML fields

I'm having some problems with getting data from HTML fields. This is how it looks in HTML
<form action="getInfo.php">
<span>Series</span>
<input class="searchFieldAlign" type="text" name="seriesName" /><Br>
<span>Volume</span>
<input class="searchFieldAlign" type="text" name="volumeName" /><Br>
<span>Nr</span>
<input class="searchFieldALign" type="text" name="issueNR" /><Br>
<p input class="searchFieldALign" type=submit></p>
</form>
This is my php script:
<?php
$seriesName = mysqli_real_escape_string($conn, $_POST['seriesName']);
$volumeName = mysqli_real_escape_string($conn, $_POST['volumeName']);
$issueNR = mysqli_real_escape_string($conn, $_POST['issueNR']);
$con=mysqli_connect("localhost","user","psswd","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qryIssueInfo = mysqli_query($con,"select issueNR, issueVolume, issueName, issueImageURL from issue, series where (seriesName='$seriesName') and (issueVolume='$volumeName') and (issueNR=$issueNR)");
$rowIssueInfo = mysqli_fetch_array($qryIssueInfo);
The problem is I don't get output from my query. There are no problems if i change it to this:
$qryIssueInfo = mysqli_query($con,"select issueNR, issueVolume, issueName, issueImageURL from issue, series where seriesName='Buffy, the Vampire Slayer' and issueVolume= 'Season 8' and issueNR=1");
If you not set form method = "post" it will be "get" and you should $_GET.
To correct:
<form method="post" action"getInfo.php">
Take it easy
The first version does not contain the apostrophes around the variables.
You should also consider security issues, like SQL injection.

saving answers in an online test and sending them to database

I'm asked to write an online test. I have 2 tables, one includes questions (2 fields, one for id and one for question text). And another table for saving answers (with 3 fields, one for id, one for question id and one for the answer).
Here's how I've written it so far:
<form name="test" method="post" action="index.html">
<div class="slideshowContainer">
$question_query=dbquery("SELECT * FROM questions");
while($question_array=dbarray($question_query)){
echo'
<div class="question">
'.$question_array['question_text'].'
<br />
<textarea name="'.$question_array['id'].'"></textarea>
</div>
';
}
echo'
<input id="finish" type="submit" name="finish_test" value="send" />
</div>
</form>';
I'm also using cycle plugin so users can see the questions as slides and write the answers in each textarea provided for each specific question.
What I can't do is the way I should write the if(isset($_POST['finish_test'])) part. Because as I know in this way, the received data is in the form of an array. So I thought I might need another for or while element when I'm gonna save the answers and send them to my database.
What can you suggest?
Sure you are gonna need to loop through the results of the $_POST but its nice to make different id for each of the text areas in your code. That way you can identify which are which answers. So to do that I would do something like this.
while($question_array=dbarray($question_query)){
i = 0;
echo'
<div class="question".i>
'.$question_array['question_text'].'
<br />
<input id='question' type='hidden' value="'.$question_array['id'].'"/>
<textarea name="answer".i></textarea>
</div>';
i++;
}
Now since I know that i starts with 0 and ends when the questions end I can loop through that and access $_POST['answer'.i] and make the insertion.
while ($_POST['answer'.$i]) {
$i = 0;
//insert query after establishing connection, which i believe you got figured out
$sql = 'INSERT INTO ANSWERS VALUES ($_POST['answer'.$i], $_POST['question'.$i])';//Note you must have the question id in some hidden input field
$result = mysql_query( $sql, $conn );//where $conn is your connection object
//after this you might want to do something with the $result,
$i++;
}

How do I search a table for multiple rows?

So this is my first question on stackoverflow and I've searched for day's but can't find the results I am looking for. I'm not looking for someone to write the code for me as I prefer to figure it out on my own, but I am looking for some assistance on finding how to do it.
My problem is I don't know how to word my search for what I'm looking for and this is what I want to do. I want to be able to search a MySQL database by using keywords such as "U10 Mustangs" where U10 would be data in a row called 'divisions' and Mustangs would be data in a row called 'club', I know I can use the OR statement like this
(`division` LIKE '%".$query."%') OR (`club` LIKE '%".$query."%')
but that only allows me to search by division or club not both. So basically I'm looking for a tutorial to show me how I can search by more than one keyword. I'm sure I'm wording this wrong and that's why I'm unable to find what I want.
I'm new to MySQL and PHP so please be understanding if this makes no sense!
*UPDATE*
here is my search code:
<body>
<?php include 'menu.php';?>
<br/><br/><br/>
<div id="searchcontainer" style="width: 55%; height: 132px;">
<fieldset style="width: 330px"><legend>Search Criteria</legend>
<form action="search.php" method="POST">
<td>Enter Search</td><td> <input type="text" name="query"/></td><td> <input type="submit" name="submit" id="table_button" value="Search" action="search.php"/></td>
<br />
</form>
</fieldset><br/>
<fieldset><legend>Search Results</legend>
<?php
include 'connect/local_connect.php';
$query = $_POST['query'];
// gets value sent over search form
// $min_length = 3;
// you can set minimum length of the query if you want
// if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM players
WHERE (`team_name` LIKE '%".$query."%' AND `division` LIKE '%".$query."%') OR (`last_name` LIKE '%".$query."%') OR (`division` LIKE '%".$query."%') ORDER by id ASC") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `first_name`, `any`
// players is the name of our table
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
}
else{ // if there is no matching rows do following
echo "<font color=red>No Results!</font>";
?><br/><br/>
<?php
}
// else{ // if query length is less than minimum
// echo "Minimum length is ".$min_length;
// }
// Define $color=1
$color="1";
echo '<table width="100%" border="1" align="center" cellpadding="0" cellspacing="0">';
echo '<th>ID</th><th>Club</th><th>Last Name</th><th>First Name</th><th>Division</th>';
while($rows = mysql_fetch_array($raw_results)){
echo "<tr bgcolor='#fff000'>
<td><center>".$rows['id']."</td></center><td><center>".$rows['club']."</center></td><td><center>".$rows['last_name']."</td></center><td><center>".$rows['first_name']."</center></td></td><td><center>".$rows['division']."</center></td></td></tr>";
}
echo '</table>';
mysql_close();
?>
</fieldset>
</div>
</body>
Are yu looking for concat
where CONCAT(`division`,' ',`club`) like '%".$query."%'
I will suggest to create a full text index on division and club like this FULLTEXT (club,division)
and search using query like this
SELECT * FROM db
WHERE MATCH (club,division)
AGAINST ('search');
'...but that only allows me to search by division or club not both...'
You can split your search string in words and then use a condition like this
SELECT *
FROM table1
WHERE (division LIKE '%U10%' AND club LIKE '%Mustang%')
OR (division LIKE '%Mustang%' AND club LIKE '%U10%')
Here is SQLFiddle demo