Store content from an html table to a mysql database - php

All i want to do is to store the user entered values to a database.There is a table and it has many text boxes where the user enters his input.Upon clicking submit button the values should be stored in the mysql table.
I'm getting some errors right now.I'm completely new to php,Below I've attached the code and screenshots.
//workingcode.php
<?php
$con = mysql_connect("localhost","tom","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//select Database
mysql_select_db("sms", $con);
$result = mysql_query("SELECT * FROM dept_info", $con) or die(mysql_error());
echo "<table border='1'>";
echo '<tr> <th>Sl No</th> <th>USN</th> <th>Name</th><th>code1</th><th>code 2</th> <th>code 3</th> <th>code 4</th> <th>code 5</th>
<th>code 6</th> <th>code 7</th> <th>code 8</th></tr>';
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['usn'];
echo "</td><td>";
echo $row['name'];
echo "</td>";
for ($i=1; $i <= 8; $i++) {
echo "<td> <input type='text' name='sl[{$row['usn']}][$i]' size='2' /> </td>" ;
}
echo '</tr>';
}
echo '
<form action = "insert.php" method = "post">
<div align="bottom">
<input type = "submit" align = "BOTTOM" value = "Proceed">
</div>
</form>
';
?>
I've linked this to an insert.php file as shown below..
<html>
<head>
<title>Marks Entry Results</title>
</head>
<body>
<h1>Student Marks Entry Results</h1>
<?php
$insertData = array();
foreach ($_POST['sl'] as $usn => $codes) {
foreach ($codes as $sl) {
$insertData[] = sprintf("('%s', %d)", mysqli_real_escape_string($usn), intval($sl));
}
}
$con = mysql_connect("localhost","tom","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//select Database
mysql_select_db("sms", $con);
$query = "INSERT INTO mytable (usn, code1) VALUES\n" . join(",\n", $insertData);
$result = mysql_query($query);
if ($result) {
echo mysql_affected_rows()." Marks inserted into database.";
} else {
echo "An error has occurred. Not added.";
}
mysql_close();
?>
</body>
</html>
//The description of the table which i made for this is
/*mysql> desc mytable;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| usn | varchar(50) | NO | PRI | NULL | |
| code1 | int(2) | YES | | NULL | |
| code2 | int(2) | YES | | NULL | |
| code3 | int(2) | YES | | NULL | |
| code4 | int(2) | YES | | NULL | |
| code5 | int(2) | YES | | NULL | |
| code6 | int(2) | YES | | NULL | |
| code7 | int(2) | YES | | NULL | |
| code8 | int(2) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
9 rows in set (0.01 sec)
*/

The textboxes are not inside any form tag so when you hit submit the value of textboxes doesn't get post back to server...Try following.
echo '<form action = "insert.php" method = "post">';
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['usn'];
echo "</td><td>";
echo $row['name'];
echo "</td>";
for ($i=1; $i <= 8; $i++) {
echo "<td> <input type='text' name='sl[{$row['usn']}][$i]' size='2' /> </td>" ;
}
echo '</tr>';
}
echo '
<div align="bottom">
<input type = "submit" align = "BOTTOM" value = "Proceed">
</div>
</form>';
//insert.php
<?php
$insertData = array();
foreach ($_POST['sl'] as $usn => $codes) {
foreach ($codes as $sl) {
$insertData[] = sprintf("('%s', %d)", mysqli_real_escape_string($usn), intval($sl));
}
}
$con = mysql_connect("localhost","tom","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
//select Database
mysql_select_db("sms", $con);
$query = "INSERT INTO mytable (usn, code1) VALUES\n" . join(",\n", $insertData);
$result = mysql_query($query);
if ($result) {
echo mysql_affected_rows()." Marks inserted into database.";
} else {
echo "An error has occurred. Not added.";
}
mysql_close();
?>

Related

How to display the comment only once but display all images from mysql in PHP?

I want to display the comment only once e.g (testsetest) with the related images (which has the same imagesid by connecting the two tables).
Example (that I want to achieve):
comment: fool with images: name1, name 2
Caption of the wrong output.
The database structure
posts:
| commentid | comment | iamgesid |
------------------------------------
| 1 | fool | 5557 |
| 2 | fool2 | 5585 |
------------------------------------
multiple_image:
| id | image | imagesid |
---------------------------
| 1 | name1 | 5557 |
| 2 | name2 | 5557 |
| 3 | name3 | 5585 |
---------------------------
This is my current code:
$sql = "SELECT image, posts.imagesid, multiple_image.imagesid, comment
FROM multiple_image JOIN posts ON (multiple_image.imagesid=posts.imagesid)";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['comment'];
$imgs= "<div id='img_div'><img width='' src='upload/".$row['image']."' ></div>";
echo $imgs;
}
}
You will need to control break the result and order by the commentid
Please see the updated code.
$sql = "SELECT
image,
posts.imagesid,
multiple_image.imagesid,
comment
FROM
multiple_image
JOIN posts ON (multiple_image.imagesid=posts.imagesid)
ORDER BY
commentid
";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
if ($result->num_rows > 0) {
// output data of each row
$comment = '';
while($row = $result->fetch_assoc()) {
if($comment != $row['comment']){
echo $row['comment'];
$comment = $row['comment'];
}
$imgs= "<div id='img_div'><img width='' src='upload/".$row['image']."' ></div>";
echo $imgs;
}
}
You can create a flag and check if it is 0. If it is 0 then you can show comment else you dont need to show comment. Check below code:
if ($result->num_rows > 0) {
// output data of each row
$loop = 0;
while ($row = $result->fetch_assoc()) {
if ($loop == 0) {
echo $row['comment'];
}
$imgs = "<div id='img_div'><img width='' src='upload/" . $row['image'] . "' ></div>";
echo $imgs;
$loop++;
}
}
Hope it helps you.
I hope it will help out:
$sql = "SELECT
image,
posts.imagesid,
multiple_image.imagesid,
comment
FROM
multiple_image
JOIN posts ON (multiple_image.imagesid=posts.imagesid)
ORDER BY
commentid";
$result = $conn->query($sql);
if (!$result) {
trigger_error('Invalid query: ' . $conn->error);
}
if ($result->num_rows > 0) {
$comment = array();
while ($row = $result->fetch_assoc()) {
// check imagesid is not exist in array
if (in_array($row['imagesid'], $comment) == false) {
echo $row['comment'];
$comment[] = $row['imagesid'];
}
$imgs = "<div id='img_div'><img width='' src='upload/" . $row['image'] . "' ></div>";
echo $imgs;
}
}

How to export to excel using php when table data and header are dynamic?

I want to export my code to excel however the header is also dynamic. Here is my code, i need assistance in exporting my data. This code below shows a dynamic table i showed in user view and needs to be exported. The view is:
"title: course/section"
"header: student id | student name | program | term | dynamic date 1 | Remarks (remarks why u are absent) including date 1 | date 2 | Remarks (remarks why u are absent) including date 2 | and so on.."
"table data: 20122222 |pinky webb |computer science | 3 | Absent | With medical certificate | present | no remark | present | no remark | late | no remark | and do on... "
"table data 2: 20122333 |Mane Sharpay|computer science | 3 | Absent | With medical certificate | present | no remark | Late | no remark | late | no remark | and so on... "
and so on...
basically, it shows the student and its attendance per date horizontally with a dynamic header of dates. sorry if im noob hehe but ill give a thumbs up i promise for ur effort
<?php
$query = "SELECT course_id, sections_id from current_att_view inner join professor_tbl on current_att_view.professor_id = professor_tbl.professor_id where professor_live_account = '".$_SESSION['username']."' group by course_id, sections_id";
$result1 = mysqli_query($link, $query);
while ($col1 = mysqli_fetch_array($result1))
{
$reslt;
echo '<h3 class="course-sect">'.$col1[0].'/'.$col1[1].'</h3>';
$qry = "Call Get_Attendance_Course_Section('".$_SESSION['username']."','".$col1[0]."','".$col1[1]."')";
$reslt = mysqli_query($link, $qry);
echo '<table class="table table-bordered">';
echo '<tr>';
if (!$reslt) {
printf("Error: %s\n", mysqli_error($link));
exit();
}
else{
while ($fieldinfo = mysqli_fetch_field($reslt)) {
if($fieldinfo->name != "Course" && $fieldinfo->name != "Section" && $fieldinfo->name != "Course Name" && $fieldinfo->name != "Schedule")
{
echo '<th>';
echo $fieldinfo->name;
echo '</th>';
}
}
echo '</tr>';
while ($rows = mysqli_fetch_array($reslt))
{
for ($i=0; $i < (count($rows)/2); $i++) {
if($i != 3 && $i != 4 && $i != 5 && $i != 6){
echo '<td>';
echo $rows[$i];
echo '</td>';
}
}
echo '</tr>';
}
echo '</table>';
mysqli_next_result($link);
}
}
// $reslt =mysqli_query($link, $qry);
?>
<input type=hidden name=date value='<?php echo date("F d, Y",strtotime($date));?>'>
<input type="hidden" name="outy" value="<?php echo $sql; ?>">
<input type="submit" name="export" value="Export" class="submit" />

POST values from multiple checkboxes to SQL

I've got two tables in mySQL.
Table: Player
-----------------------------------------------------------
| name | T1 | T2 | T3 | T4 | T5 | id | weeknumber |
|--------|----|-----|-----|-----|-----|-----|-------------|
| | | | | | | | |
| | | | | | | | |
-----------------------------------------------------------
Table: Teams
-------------------------------------------------------------------------
| id | team1name | team2name | team1score | team2score | weeknumber |
|------|-----------|-----------|-------------|------------|-------------|
| | | | | | |
| | | | | | |
-------------------------------------------------------------------------
The idea is, that table "Teams" is getting populated through another page that already works for me.
Every week there will be 13 new teams.
Table "Player" has to get populated from another page where the user gets the following options:
Name: Text-field
13 Checkboxes (those checkboxes need to store the value ID from table Teams)
The user is supposed to check 5 out of 13 teams (free choice) and the values of those checkboxes (the ID of the Teams ID) should be stored as T1, T2, T3, T4, T5 along with Name from text-field.
<form method="post" action="created.php" class="form-style-7">
<h2>Tilmeld en spiller </h2>
<ul>
<li>
<label for="name">Navn</label>
<input type="text" name="navn" value="<?php echo $navn;?>">
<span>Indtast spillerens navn</span>
</li>
<li>
<?php
$count = $rows = 0;
$sql = "SELECT * FROM Teams WHERE weeknumber='$WeekNumber' ORDER BY id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '
<table class=""><tr><th colspan="3">Igangværende - Uge ' . $WeekNumber . '</th></tr>
<tr class="underhead"><td>#</td><td>Kamp</td><td>Mål</td></tr>
';
// Output af data
while($row = $result->fetch_assoc()) {
if ($rows % 1 == 0) {
$count++;
}
$rows++;
echo '<tr>';
echo '<td>';
echo '';
echo '<input type="hidden" name="ID" value="' . $row['id'] . '" >';
echo '<input class="btn" type="checkbox" name="" > ';
echo ' </form>';
echo '</td>';
echo '<td>' . $count . '</td>';
echo '<td>' . $row["team1name"]. ' - ' . $row["team2name"] . '</td>
</form>';
}
echo '</table>';
}
mysqli_close($conn);
?>
</li>
<li id="buttontilmeld">
<input type="submit" name="submit" value="Tilmeld" >
</li>
</ul>
</form>
Edit:
My created.php contains the following:
if (isset($_POST['navn']) && $_POST['navn'] != "") {
if (isset($_POST['navn'])) {
if ($_POST['name'] == "" || $_POST['T1'] == "" || $_POST['T2'] == "" || $_POST['T3'] == "" || $_POST['T4'] == "" || $_POST['T5'] == "") {
echo 'XX';
}
} else {
require 'config.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['navn']);
$match1 = $conn->real_escape_string($_POST['kamp1']);
$match2 = $conn->real_escape_string($_POST['kamp2']);
$match3 = $conn->real_escape_string($_POST['kamp3']);
$match4 = $conn->real_escape_string($_POST['kamp4']);
$match5 = $conn->real_escape_string($_POST['kamp5']);
$WeekNumber = date('W');
$query = "INSERT into Spillere (navn,kamp1,kamp2,kamp3,kamp4,kamp5,ugenummer) VALUES('" . $name . "','" . $match1 . "','" . $match2 . "','" . $match3 . "','" . $match4 . "','" . $match5 . "','" . $WeekNumber . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
echo "Thanks";
}
}
}
Where I need $_POST['TX']=="" to populate table Player T1 to T5.
The name attribute of the checkboxes are not set. PHP can't get any info about the checked checkboxes (unless you should use Jquery en do some other stuff). It's important to know that only checked checkboxes will be visible in the POST data.
Give your checkboxes a name, for example:
echo '<input class="btn" type="checkbox" name="team_checkbox_'.$row['id'].'"> ';
Then in the script created.php were your data is posted to you can catch these values by running the same SQL-query and trying
if(isset($_POST['team_checkbox_'.$row['id']])){
// $row['id'] is checked
}
Or just check all POST data:
$t = array();
foreach($_POST as $post_param_name => $value){
if(substr($post_param_name, 0, 14) == 'team_checkbox_'){
// substr($post_param_name, 14) is the ID of one of the checked groups
$t[] = substr($post_param_name, 14);
}
}
Now $t is an array containing the team ID's of the checkboxes. So you can save in your SQL: T1 = $t[1], ...
This answer should be reviewed, but the solution is in another answer here:
https://stackoverflow.com/a/47162431/1589379
Follow good coding standards
There's a lot of little problems with the code you posted. Ultimately, you should always be very careful to keep everything properly indented, and always use brackets {}, even if they're not needed.
Your original code:
while (...) {
if ($rows % 1 == 0)
$count++;
Should be:
while (...) {
if ($rows % 1 == 0) {
$count++;
}
Those adjustments would have made it much more clear that your code had two closing </form> tags, and no opening tags, within your while loop.

Get data from MySQL database table by specific field in url

Im new to PHP MySQL. Im developing a songbook site.
I want to create tables alphabetically in separate pages for each alphabet.
When a user click an alphabet in the menu it will direct to this page site/publicsearch.php?browse=a
This is the database :
| ID | TITLE | ARTIST | CATEGORY | ALPHABET |
+----------------------------------------------------+
| 1 | Amazing love | XXXXXX | Love | a |
| 2 | Above all | XXXXXX | Worship | a |
| 3 | BXXXX | XXXXXX | Love | b |
| 4 | BXXXX | XXXXXX | Worship | b |
I pull the above database table like this : It works fine.
<?php
$servername = "localhost";
$username = "xxxxxxx";
$password = "xxxxxxxx";
$db_name = "xxxxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "Connected successfully";
exit();
}
// Attempt select query execution
$sql = "SELECT * FROM lyrics_a";
if($result = mysqli_query($conn, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table class='table'>";
echo "<tr>";
echo "<th>#</th>";
echo "<th>Title</th>";
echo "<th>artist</th>";
echo "<th>cateogry</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td> " . $row['eng_title'] . " " . $row['tel_title'] . " </td>";
echo "<td>" . $row['artist'] . "</td>";
echo "<td>" . $row['category'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
I need separate alphabetical tables like this :
Alphabet "a" table results `site/publicsearch.php?browse=a`
| ID | TITLE | ARTIST | CATEGORY | ALPHABET |
+----------------------------------------------------+
| 1 | Amazing love | XXXXXX | Love | a |
| 2 | Above all | XXXXXX | Worship | a |
Alphabet "b" table results `site/publicsearch.php?browse=b`
| ID | TITLE | ARTIST | CATEGORY | ALPHABET |
+----------------------------------------------------+
| 3 | BXXXX | XXXXXX | Love | b |
| 4 | BXXXX | XXXXXX | Worship | b |
I tried the below code doesn't work.
<?php
$servername = "localhost";
$username = "xxxxxx";
$password = "xxxxxxx";
$db_name = "xxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $db_name);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$alphabet = $_GET['alphabet'];
$id = mysqli_real_escape_string($conn,$id);
$query = "SELECT * FROM `lyrics` WHERE `alphabet`='" . $alphabet . "'";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result)) {
echo "<br><br>";
echo $row['id'];
echo $row['title'];
echo $row['lyrics'];
echo $row['alphabet'];
}
?>
I'm newbie. Please help. Thank you.
$alphabet = $_GET['alphabet'];
$id = mysqli_real_escape_string($conn,$id);
$query = "SELECT * FROM `lyrics` WHERE `alphabet`='" . $alphabet . "'";
replace with:
$alphabet = mysqli_real_escape_string($conn,$_GET['browse']);
$query = "SELECT * FROM `lyrics` WHERE `alphabet`= '" . $alphabet . "' ";
You propose the following URL: publicsearch.php?browse=a
But in your script you are using the request parameter $_GET['alphabet']
In addition, you don't need a separate column alphabet in your database, you can use SQL's LIKE:
$letter = $_GET['browse'];
$sql = "SELECT * FROM `lyrics` WHERE title LIKE '{$letter}%'"

How do I update a row in the database with the data from website?

I am trying to assigned each student with a company from a drop down list and have it updated in the database under the correct student.
So basically, this is how my website looks like.
___________________________________________________________________
| Student ID | Admin No | Student Name | Company List |
| 1 | 1234 | ABC | <drop down list> |
| 2 | 2345 | BCD | <drop down list> |
| 3 | 3456 | CDE | <drop down list> |
| 4 | 4567 | DEF | <drop down list> |
And this is the codes for the table above.
<form name="IT" action="getIT_now.php" method="post">
<table cellspacing="0">
<tr>
<th>Student ID</th>
<th>Admin Number</th>
<th>Student Name</th>
<th>GPA</th>
<th>Gender</th>
<th>Company List</th>
</tr>
<?php
$con=mysqli_connect("....","....","....",".....");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create the query
$result = mysqli_query($con,"SELECT student_id, admin_no, name, GPA, gender FROM student_details WHERE jobscope1= 'Information Technology' ORDER BY `GPA` DESC; ");
$result2 = mysqli_query($con,"SELECT job_title FROM job_details WHERE jobscope='Information Technology' ORDER BY `job_title` ASC;");
/*options sections start*/
$options= '';
while ($row2 = mysqli_fetch_assoc($result2))
{
$options .='<option value="'. $row2['job_title'] .'"> '. $row2['job_title'] .'</option>';
}
/*options sections end*/
//return the array and loop through each row
while($row = mysqli_fetch_assoc($result))
{
$studentid = $row['student_id'];
$adminno = $row['admin_no'];
$name = $row['name'];
$gpa = $row['GPA'];
$gender = $row['gender'];
echo "<tr>";
echo "<td>" . $studentid . "</td>";
echo "<td>" . $adminno . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $gpa . "</td>";
echo "<td>" . $gender . "</td>";
echo "<td><select name='ddl' onclick='if(this.value != '') { myform.submit(); }'>".$options."</select></td>";
}
echo "</tr>";
?>
</table>
<input type='submit' value='Submit Pick' />
</form>
Now this form will actually go to another page since I have include a form action.
So the codes in this getIT_now.php page is
<?
$con=mysqli_connect("...","....","....","....");
if (!$con)
{
die('Could not connect: ' . mysqli_errno());
}
$ddlvalues = $_POST['ddl'];
$studentid = $_POST['student_id'];
$query = mysqli_query($con, "INSERT INTO student_details(company) VALUES('" . $ddlvalues . "');");
?>
However, when I check the database, only the first option in the drop down list is reflected in a new row. I have tried to use the UPDATE query statement, but it is wrong.
This is the query for the UPDATE statement.
UPDATE student_details SET company = '" . $ddlvalues . "' WHERE student_id = '" . $studentid . "';
The problem I'm having right now is actually:
How do I make Student ID on the website and in the database to match so that it can update correctly?
Why is it that only the first option in the drop down list is reflected when I use the INSERT query?
I am quite new to PHP so I am really struggling with this.
You don't have an input that holds the student_id, i.e $_POST['student_id'] is not set, also you would have to validate the user inputs before you pass them to query, You can use prepared statements,
Try with a hidden field like
echo '<input type="hidden" name="student_id" value="'.$studentid.'"/>';

Categories