Printing a table somewhat complex MYSQL query in PHP - php

I have a database with 2 tables User, Contact_List.
The User table for example looks like this:
U_id | U_email | U_password | U_mobileNo | U_name |
---------------------------------------------------
1 | a#b.c | aaa | 1234567 | Adam |
2 | b#b.c | bbb | 1234567 | Ben |
3 | c#b.c | ccc | 1234567 | Carl |
The Contact_list table looks like this. This table is table just consisting of foreign keys that relate two users together
U_id | U_contact_id
-------------------
1 | 2
2 | 3
Now the problem is my SQL/PHP query to display a table that consists of a specific users list of contacts.
This SQL query works fine and gives the results I want:
"SELECT cu.u_name, cu.u_email
FROM contact_list = c, user = u, user = cu
WHERE c.u_id = 2
AND c.u_contactId = c.u_id
AND c.u_id = u.u_id"
But this PHP code:
$con = mysqli_connect("dbname","dbuser","pbpass","db");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT cu.u_name, cu.u_email
FROM contact_list = c, user = u, user = cu
WHERE c.u_id = 2
AND c.u_contactId = c.u_id
AND c.u_id = u.u_id" ) or die(mysql_error());
echo "<table border='1'>
<th>Contact List</th>
<tr>
<th>Name</th>
<th>E-mail</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['u_name'] . "</td>";
echo "<td>" . $row['u_email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
mysqli_close($con);
?>
That code just prints a blank table on the page.
What am I doing wrong here?
I am a complete noob using PHP any help or suggestions would be appreciated.

You want to retrieve all the contacts of user with id 2 so basically your query would look like this:
SELECT u.u_name, u.u_email
FROM contact_list cl
JOIN user u
ON cl.u_contact_id = u.u_id
WHERE cl.u_id = 2
Live DEMO.
What the above query does is, it will join the users information based on the u_contact_id and will list all the names and emails registered to it.
And your PHP would look like this:
<?php
// your database info here
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
if (!$stmt = $con->prepare("SELECT u.u_name, u.u_email
FROM contact_list cl
JOIN user u
ON cl.u_contact_id = u.u_id
WHERE cl.u_id = ?"))
die('Prepare Error: ' . $con->error);
$id = 2;
if (!$stmt->bind_param('i', $id))
die('Bind Parameters Error ' . $stmt->error);
if (!$stmt->execute())
die('Select Query Error ' . $stmt->error);
?>
<table border="1">
<th>Contact List</th>
<tr>
<th>Name</th>
<th>E-mail</th>
</tr>
<?php
$stmt->bind_result($name,$email);
while ($stmt->fetch())
{
?>
<tr>
<td><?php echo $name; ?></td>
<td><?php echo $email; ?></td>
</tr>
<?php
}
echo "</table>";
$stmt->close();
$con->close();

Try to do a var_dump on $row, you may find out more on what went wrong, if no var_dump appears, no result return was returned, use mysqli_error to find out what went wrong
mysqli_error($con);
while($row = mysqli_fetch_array($result))
{
var_dump($row);
}
It could be a case issue
$row['u_name']
may be is
$row['U_name']

SELECT cu.u_name, cu.u_email
FROM contact_list c, user u, user cu
WHERE c.u_id = 2
AND c.u_contactId = c.u_id
AND c.u_id = u.u_id
Maybe it's just that I suffer insomnia, but that should work

In your query:
Your syntax for specifying table alias is wrong. There is no need for the = sign.
You are aliasing user as both u and cu, but seems like you can get by with just one.
Try the following:
SELECT cu.u_name, cu.u_email
FROM contact_list c, user u // Or alternatively: FROM contact_list AS c, user AS u
WHERE c.u_id = 2
AND c.u_contactId = c.u_id
AND c.u_id = u.u_id
By the way, when printing the <table>, you need to place <th> inside <tr> for valid HTML.
Also, in your $result = mysql_query (....) you ended it with or die (mysql_error()). It should be or die (mysqli_error()).

Related

How to query data from two tables from mysql database and display one HTML table

I have two tables... Only $sql is executing. How do I get $sql2 to query also? $sql2 is storing the secondID with the current_timestamp in the database but not receiving any input from 'serialnumber.' Only the first $sql is querying and storing in the database.
+--------------+
| SafetyAtt |
+--------------+
| SecondID |
| SerialNumber |
+--------------+
+---------+
| Safety |
+---------+
| ID |
| DateLog |
| Topic |
+---------+
<table>
<thead>
<tr align="left">
<th>Seq</th>
<th>Date</th>
<th>Topic</th>
<th># of Attendees</th>
<th>Add Attendee</th>
</tr>
</thead>
<?php
$sql = "SELECT ID, DateLog, Topic FROM Safety";
$sql2 = "SELECT secondID, SerialNumber FROM SafetyAtt";
$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 "<tr><td>" . $row["ID"]. "</td><td>" . $row["DateLog"] . "</td><td>"
. $row["Topic"] . "</td><td>" . $row["secondID"] . "</td><td>" ?>
Serial Number: <input type="text" name="serialnumber" placeholder="Enter serial #"> <?php " . </td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</table>
You have to JOIN your two tables and it should have one query. First you select the columns you want to get, then join the tables by using the foreign key or something else that is common in the two tables. For example,
"SELECT car.id, driver.name, driver.age FROM car INNER JOIN driver ON car.driverID=driver.driverID"
see this link to more about SQL JOINS.

Update Table 1 rows with table 2 rows Where table 2 have to fetch from database

Table 1 (Which needs to be updated)
+-----------------+
|name |qty |
+-----------------+
|area | 1 |
|length | 2 |
|breadth | 3 |
|width | 4 |
+-----------------+
Table Which needs to be fetched for what values and rows have to be update
+-------------------------------------+
|name | upd_qty | Cart_id | cid |
+-------------------------------------+
|area | 6 | 12 | 1 |
|length | 8 | 20 | 2 |
|breadth | 11 | 34 | 3 |
+-------------------------------------+
How can i do this using php. Help me with this please.
this is the code i have used for my original work. Table 1 & Table 2 have name in common and conditions are
1 . UPDATE should done for the rows which are fetched from table to with where condition.
2. Table 2 upd_qty will be updated in table 1 qty while fetching data from table 2 where condition.
$con=mysqli_connect("localhost","root","","medical");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
error_reporting(E_ALL ^ E_NOTICE);
$query = "SELECT * FROM cart WHERE cid='$id' AND 'cart'='$cart_id'";
$result = $con->query($query);
while($row = $result->fetch_assoc()) {
$mediname = $row['name'];
$mediqty = $row['upd_qty'];
for($i=0;$i<$count;$i++){
$sql="UPDATE stock SET qty='$mediqty' WHERE name='$mediname' AND
'cart'='$cart_id'";
if (!mysqli_query($con,$sql))
{
die('Error: Failed' . mysqli_error($con));
}
I don't think you need this line:
for($i=0;$i<$count;$i++){
There's already a "while fetch" loop.
Also, don't use single quotes around identifiers, use backticks if the identifier needs to be escaped.
With this:
... AND 'cart' = ...
'cart' will be evaluated a string literal, not a column reference.
With this
... AND `cart` = ...
cart is an identifier, a reference to a column.
Also, if we can't use prepared statements with bind placeholders, at a minimum, we use mysqli_real_escape_string to mitigate SQL Injection vulnerabilities
Also, there's a confusing mix of procedural style and objected oriented style calls...
procedural style
mysqli_query($con,$sql)
mysqli_error($con)
object oriented style
$con->query($query)
$result->fetch_assoc()
I recommend you choose one style or the other, and stick to that pattern.
$query = "SELECT * FROM cart WHERE `cid` = '"
. $con->real_escape_string($id)
. "' AND `cart` = '"
. $con->real_escape_string($cart_id)
. "'";
$result = $con->query($query);
if( !$result ) {
die('Error: ' . $con->error());
}
while( $row = $result->fetch_assoc() ) {
$mediname = $row['name'];
$mediqty = $row['upd_qty'];
$sql="UPDATE stock SET `qty` = '"
. $con->real_escape_string($mediqty)
. "' WHERE `name` = '"
. $con->real_escape_string($mediname)
. "' AND `cart` = '"
. $con->real_escape_string($cart_id)
."'";
if(!$con->query($sql) ) {
die('Error: Failed' . $con->error());
}
}
EDIT
If there's not a specific reason for the loop, if the goal is just to perform the UPDATE operation and there is not other logic or conditions, we can do the UPDATE in one statement, without a need for multiple query executions:
UPDATE cart c
JOIN stock s
ON s.cart = c.cart
AND s.name = c.name
SET s.qty = c.upd_qty
WHERE c.cid = ?
AND c.cart = ?
Personally, I would just do the one UPDATE statement using a prepared statement
// connect to mysql
$con = new mysqli(...)
if( $con->connect_error ) {
die( 'Connect error: ' . $con->connect_error );
}
// update statement
$sql = '
UPDATE cart c
JOIN stock s
ON s.cart = c.cart
AND s.name = c.name
SET s.qty = c.upd_qty
WHERE c.cid = ?
AND c.cart = ? ';
$sth = $con->prepare($sql);
if(!$sth) {
die( 'Prepare error: ' . $con->error() );
}
$sth->bind_param('ii',$id,$cart_id);
if(!$sth->execute()) {
die( 'Execute error: ' . $con->error() );
}
Code worked for me for what i want exactly is :
$con=mysqli_connect("localhost","root","","medical");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
error_reporting(E_ALL ^ E_NOTICE);
$query = "SELECT * FROM cart WHERE cid='$id' AND cart='$cart_id'";
$result = $con->query($query);
while($row1 = $result->fetch_assoc())
foreach ($result as $row1){
$sql="UPDATE stock SET qty='$row1[upd_qty]' WHERE name='$row1[name]'";
if (!mysqli_query($con,$sql))
{
die('Error: Failed' . mysqli_error($con));
}
}

joining 4 tables in mysql statement in php

i dont know how to explain it well but what i want is that i want to display the instrutors name and courses title in my subject table and the day&time of the subject and at first i can display the subjects with its instructor name and course title but when i display the day&time of it.it dont fit on my desired output..
here is my sample code:
//subjectClass.php
public function subjects(){
global $db;
$sql = "
SELECT s.*
, i.first_name
, i.mid_name
, i.last_name
, c.course_title
, d.sub_day
, d.start_time
, d.end_time
FROM subjects_tbl s
LEFT
JOIN instructors_tbl i
ON i.instructor_id = s.instructor_id
LEFT
JOIN courses_tbl c
ON c.course_id = s.course_id
LEFT
JOIN subject_day_tbl d
ON d.subject_id = s.subject_id;
";
$query = $db->query($sql);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$list[] = $row;
}
}else{
$list = NULL;
}
return $list;
}
//subjects.php
//include 'subjectsClass.php';
<table class="table table-condensed table-bordered">
<thead>
<tr>
<th>Subject Code</th>
<th>Subject Title</th>
<th>Unit</th>
<th>Section</th>
<th>Course</th>
<th>Instructor</th>
<th>Day/Time</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$subjectsClass = new subjectsClass;
$subjects = $subjectsClass->subjects();
foreach ($subjects as $key => $value) {
?>
<tr>
<td><?php echo $value['subject_code']; ?></td>
<td><?php echo $value['subject_title']; ?></td>
<td><?php echo $value['unit']; ?></td>
<td><?php echo $value['section']; ?></td>
<td><?php echo $value['course_title']; ?></td>
<td><?php echo $value['first_name'] . " " . $value['mid_name'] . ". " . $value['last_name'] ; ?></td>
<td>
<?php echo $value['sub_day'] . " [" . $value['start_time'] . " - " . $value['end_time'] . "]<br />"; ?>
</td>
<td>Edit | Delete</td>
</tr>
<?php
}
?>
</tbody>
and here is the output:
Subject Code Subject Title Unit Section Course Instructor Day/Time
ITE 131 Security Issues and Principles 3 IT-R BSIT Darwin Paradela. Galudo Monday [07:30:00 - 09:00:00]
ITE 131 Security Issues and Principles 3 IT-R BSIT Darwin Paradela. Galudo Wednesday [08:30:00 - 10:00:00]
ITE 050 Database Management System 2 3 IT-R BSIT Ronnie Pitt. Cambangay Tuesday [07:00:00 - 08:30:00]
ITE 050 Database Management System 2 3 IT-R BSIT Ronnie Pitt. Cambangay Thursday [07:00:00 - 08:30:00]
my desired output is this one:
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
| Subject Code | Subject Title | Unit | Section | Course | Instructor | Day/Time |
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
| ITE 131 | Security Issues and Principles | 3 | IT-R | BSIT | Darwin Paradela. Galudo | Monday [07:30:00 - 09:00:00] |
| | | | | | | Wednesday [08:30:00 - 10:00:00] |
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
| ITE 050 | Database Management System 2 | 3 | IT-R | BSIT | Ronnie Pitt. Cambangay | Tuesday [07:00:00 - 08:30:00] |
| | | | | | | Thursday [07:00:00 - 08:30:00] |
+--------------+--------------------------------+------+---------+--------+-------------------------+---------------------------------+
my tables:
subjects_tbl
courses_tbl
instructors_tbl
subject_day_tbl
I hope I can help you.
Your issue seems to be the left join of subject_day_tbl. It is a one-to-many relationship (ie, there can be many records in subject_day_tbl for each record in subjects_tbl), and when you left join a one-to-many you'll get a duplicate of the "one" side for each row in the "many" side. The only way that you could do this in a single query is by using a subquery or group statement to concatenate the rows in the database engine... but that is really bad because you're mixing display with your data model.
While it is true in general that for performance one should avoid issuing too many queries to the database, premature optimization is the root of all evil. First, try to have clean, understandable code, then look for bottlenecks if you're having issues.
In this case, a second query is certainly best. This is how I would do it:
//subjectClass.php
protected function subject_days($subject_id)
{
// I don't know what type of object $db is it looks like ezSQL,
// but you get the idea
global $db;
$sql = "SELECT sub_day, start_time, end_time
FROM subject_day_tbl
WHERE subject_id = %s";
$query = $db->query($db->prepare($sql, $subject_id));
return ($query->num_rows > 0) ? $stmt->fetch_assoc() : array();
}
public function subjects()
{
global $db;
$sql = "SELECT s.*
, i.first_name
, i.mid_name
, i.last_name
, c.course_title
, d.sub_day
, d.start_time
, d.end_time
FROM subjects_tbl s
LEFT JOIN instructors_tbl i
ON i.instructor_id = s.instructor_id
LEFT JOIN courses_tbl c
ON c.course_id = s.course_id
";
$list = array();
$query = $db->query($sql);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
$row['course_days'] = $this->subject_days($row['subject_id']);
$list[] = $row;
}
}
return empty($list) ? NULL : $list;
}
// subjects.php
$subjectsClass = new subjectsClass;
$subjects = $subjectsClass->subjects();
foreach ($subjects as $key => $value) {
?><tr>
<td><?php echo $value['subject_code']; ?></td>
<td><?php echo $value['subject_title']; ?></td>
<td><?php echo $value['unit']; ?></td>
<td><?php echo $value['section']; ?></td>
<td><?php echo $value['course_title']; ?></td>
<td><?php echo $value['first_name'] . " "
. $value['mid_name'] . ". "
. $value['last_name'] ; ?></td>
<td><?php foreach($value['course_days'] as $day) {
echo $value['sub_day'] . " [" . $value['start_time'] . " - " . $value['end_time'] . "]<br />";
}?></td>
<td>Edit | Delete</td>
</tr><?php
}
Also, not to be a pedant, but you should really be escaping your output before
echoing it, eg with htmlspecialchars.

PHP/MySQL Relationships / Echo Field

I'm trying to build my 1st relationship database and it looks like this so far:
Relationships Table
Partners Table
Location Table
I want to echo all the row info including the related location names on my page, how would I get the following to echo?
ID: 2 Name: Salisbury Removals Locations: Salisbury
ID: 4 Name: Inbetween Removals Locations: Salisbury, Southampton
ID: 5 Name: Southampton Removals Locations: Southampton
=====SOLVED!=====
$sql = "SELECT partner_id, partner_name, email_address, active FROM partners WHERE active ='yes' ORDER BY partner_id ASC";
$connect->query($sql);
if ($partners = $connect->query($sql)) {
foreach ($partners as $partner) {
echo '<li><ul>';
echo '<li>' . $partner['partner_id'] . '</li>';
echo '<li>' . $partner['partner_name'] . '</li>';
echo '<li>' . $partner['email_address'] . '</li>';
echo '<li>' . $partner['active'] . '</li>';
// START GET LOCATIONS FROM RELATED TABLE
echo '<ul>';
$sql2 = "SELECT p.partner_name AS Name, p.partner_id AS ID, l.location_name AS Locations from partners_locations r, partners p, locations l WHERE p.partner_id = r.partner_id AND l.location_id = r.location_id AND r.partner_id =" . $partner['partner_id'] . "";
$connect->query($sql2);
if ($locations = $connect->query($sql2)) {
foreach ($locations as $location) {
echo '<li>' . $location['Locations'] . '</li>';
}
} else {
echo "Error: No Locations<br>";
}
echo '</ul>';
// END GET LOCATIONS FROM RELATED TABLE
echo '</ul></li>';
}
} else {
echo "Error: No Active Partners<br>";
}
The best thing you could do is make a new table to contain the partner_id and location_id.
tbl_relationships_new
Pros for this approach :-
1).When you need to remove a location from a partner, you wouldn't need to edit the column locations. You could simply delete an entry from this new table.
2). When you need to add more data in the locations field, you could simply just insert into the new table, which is rather easy than having to update partners.locations.
Now, you could use easy left joins to get the required data.
SQL query for my table solution.
SELECT t.*,p.*,l.* FROM tbl_relationships_new t, partners p, locations l LEFT JOIN
partners
ON
t.partner_id = p.partner_id
LEFT JOIN
locations
ON
l.location_id = t.location_id
WHERE
t.partner_id = 2
UPDATE
Here are the queries based on your table structure.
1). ID: 2 Name: Salisbury Removals Locations: Salisbury
SELECT p.partner_name AS Name, p.partner_id AS ID, l.location_name AS Locations from relationships r, partners p, locations l WHERE p.partner_id = r.partner_id AND l.location_id = r.location_id AND r.partner_id = 2
2). When there are 2 locations.
SELECT p.partner_name AS Name, p.partner_id AS ID, l.location_name AS Locations from relationships r, partners p, locations l WHERE p.partner_id = r.partner_id AND l.location_id = r.location_id AND r.partner_id = 5
UPDATE
Solution without explicitly mentioning an ID.
SELECT p.partner_name AS Name, p.partner_id AS ID, l.location_name AS Locations from relationships r, partners p, locations l WHERE p.partner_id = r.partner_id AND l.location_id = r.location_id
<?php
$dbconn = mysqli_connect(DBSERVER, DBUSER, DBPWD, DBNAME);
$sql = "SELECT partner_id, partner_name, locations FROM Partners";
$result = mysqli_query($dbconn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: ".$row['partner_id']." Name: ".$row['partner_name']." Locations: ";
$locs = explode(",",$row['locations']);
$first = true;
foreach ($locs as $loc) {
$sql2 = "SELECT location_name FROM Locations WHERE location_id = '".$loc."'";
$result2 = mysqli_query($dbconn, $sql2);
$row2 = mysqli_fetch_assoc($result2);
$separator = ($first?"":", ");
$first = false;
echo $separator.$row2['location_name'];
}
echo "<br/>";
}
?>
First your table Table: Partners entry should be like this.
partener_id | partner_name | email_address | active | location_id
2 Test Partner ....... yes 1
5 Good Removals ....... yes 1
5 Good Removals ....... yes 2
4 Special Removals ....... yes 2
So, you could make join with Table: Locations.
After that execute below sql query.
$sql = "select * from partners Left join locations on locations.location_id=partners.location_id";
For better understanding of query execution and data display. follow below link.
http://www.w3schools.com/php/php_mysql_select.asp
Your "locations" field in the Partners table is wrong, you must create another table to handle relations between Partners and Locations, called Locations_Partners par example. This table must have 2 fields, location_id and partner_id. This way, you can relate many partners with many locations. Then, you code should look like this:
<?php
$servername = "www.server.com";
$username = "username";
$password = "password";
$dbname = "your database name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT partner_id, partner_name, location_name FROM Partners
INNER JOIN Locations_Partners ON Partners.partner_id = Locations_Partners.Partner_id
INNER JOIN Locations ON Locations_Partners.Location_id = Locations.location_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["partner_name"]. " " . $row["location_name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

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