I'm doing a school project - a website with students performances in various sports. I have three tables:
TABLE1 - "students"
id (primary key)
class
firstname
lastname
TABLE2 - "sports"
sport_id (primary key)
sportname
TABLE3 - "performances"
performance_id (primary key)
sport_id (foreign key - sports.sport_id)
student_id (foreign key - students.id)
value
I want to make a form that adds data into the third table.
That form should include:
class
firstname
lastname
sportname
value
...but I have no idea how to achieve this.
I could just create a form where user user adds value and then copy-pastes sport_id and student_id from tables below it, but that's unpractical.
I've been searching the internet for a while, but I haven't found any solution to this and if I did, it was only for one foreign key.
Does anyone know how to do this? If so, I would highly appreciate it! :)
EDIT: I should've mentioned that tables "students" and "sports" already have all the data in them, I just need to insert new performances using that data.
Since the data is already in the tables for students and sports, this information can be queried with some select statements in order to populate some HTML dropdowns. The advantage of using the select queries and the dropdowns is that value of the options can be set to the database ID while showing the user the human-readable text. Then, the page just needs to monitor for the form's submission and insert the IDs from the dropdowns along with the performance metric. I have not tested the code below, but here is a quicky example of how that might work.
Note: I like the PDO interface for preparing SQL queries in order to prevent injection attacks.
<?php
$user = 'user';
$password = 'password';
$con = new PDO('mysql:dbname=dbname;host=127.0.0.1;chartset=urf8', $user, $password);
$student_stmt = $con->prepare('select * from students');
$student_stmt->execute();
$sport_stmt = $con->prepare('select * from sports');
$sport_stmt->execute();
if (isset($_GET['student']) && isset($_GET['sport']) && isset($_GET['value'])) {
$student = $_GET['student'];
$sport = $_GET['sport'];
$value = $_GET['value'];
$insert_stmt = $con->prepare('insert into preformances (sport_id, student_id, value) values (:sport_id, :student_id, :value)');
$insert_stmt->bindParam(':sport_id', $sport);
$insert_stmt->bindParam(':student_id', $student);
$insert_stmt->bindParam(':value', $value);
$insert_stmt->execute();
}
?>
<html>
<head>
<title>Form</title>
</head>
<body>
<form action="self.php" method="get">
Student:
<select name="student">
<?php while ($row = $student_stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['firstname'] . " " . $row['lastname']; ?></option>
<?php } ?>
</select>
Sport:
<select name="sport">
<?php while ($row = $sport_stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<option value="<?php echo $row['sport_id']; ?>"><?php echo "$row['sportname']"; ?></option>
<?php } ?>
</select>
Performance: <input name="value" type="text" />
<button type="submit">Submit</button>
</form>
</body>
</html>
Edit:
Made the changes in the code in the suggested comment.
I think all you need to do is to get input values from your form ($variable = $_GET["classinput"];) and then connect to database and write mysqli query with input query for every table.
like this:
$query = mysqli_query($connection, "INSERT INTO STUDENTS(id,class,firstname,lastname) VALUES (null,\"$class\",\"$firstname\",\"$lastname\")");
And do this for all your tables.
Related
So I am attempting to create an HTML drop-down list. The list is fine--and it shows all of my desired options from a MySQL query of it's own; however my next step was to set the default value (which is the current landlord) for the tenant.
Now, I am able to successfully, but only with the landlords key (which is in a separate table). I have a second query that looks up the landlord's name based on the key, and I cannot even get it to echo out a response. I must assume the query is bad--but after looking at the same lines of code the entire morning, I believe I can confidently say it is not. I am hoping a second set of eyes will see something I do not.
Getting the current landlord for the tenant:
$sql = mysql_query("SELECT data_txt FROM field_data WHERE itemid = $uid AND fieldid = 16");
$row = mysql_fetch_array($sql);
$ll1 = $row[0];
$sql = mysql_query("SELECT info FROM landlords WHERE key = $ll1 LIMIT 1");
$row = mysql_fetch_array($sql);
$ll1_name = $row[0]
Setting the default value in the Dropdown-list:
I don't believe the problem lies here, since I cannot do anything as simple as echo the variable $ll1_name; but I feel it's worth including.
<td>
<?php echo "$ll1"; ?><br>
<?php echo "$ll1_name"; ?><br>
<select name=ll1>
<option value="<?php echo "$ll1"; ?>"> <?php echo "$ll1_name"; ?></option>
<?php
while ($curLandlord = mysql_fetch_array($landlordRows)){
?>
<option value="<?php echo "$curLandlord[0]"; ?>"> <?php echo "$curLandlord[1]"; ?></option>
<?php
}
?>
</select>
</td>
Also, I am well aware that this library is depreciated and my fields are not sanitized, etc. I am just making this as simple as possible, and then implementing that after I have a working model. The fewer variables, the better.
The following is an example of the table data:
Landlords
key, info, id (auto increment)
-*key*: ll1_07
-*info*: John Doe
-*id*: 77
field_data
id, fieldid, data_txt, itemid
-*id*: 1234 (auto increment)
-*fieldid*: 18 (each fieldid corresponds to a field name in another table. 18 is landlord)
-*data_txt*: ll1_77
-*itemid*: 33 (tenants unique ID)
No, it's not "correct". You have an sql injection vulnerability. Just because your $ll1 value came out of the DB doesn't mean it's safe to REUSE in another query. You're doing the equivalent of
SELECT info FROM landlords WHERE key = foo LIMIT 1
^^^---unknown/illegal field name
instead of
SELECT info FROM landlords WHERE key = 'foo' LIMIT 1
^^^^^--string literal
If you had even BASIC error handling on your query calls, you'd have been informed of this:
$sql = mysql_query("SELECT [..snip..]") or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
Never EVER assume success on a query. Even if the sql is 100% syntactically correct, there's a near infinite number of reasons for it to STILL fail (biggest one: missing foreign key).
Try this and see what the response is:
$sql = "
SELECT
fd.data_text,
l.info
FROM
field_data fd
JOIN
landlords l
ON fd.data_text = l.key
WHERE
fd.itemid = $uid
AND fd.fieldid = 16
LIMIT 1";
$rs = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($rs);
var_dump($row);
That should tell you if you are getting any data back.
Good evening, I am currently working on the website where there are two entities students and admins. I am attempting to have the admins have the ability to view a specific student's detail page.
I am having difficulties while attempting to have two sessions running at the same time (one would be the logged in admin, and two would be the "selected student's id" which would be saved when selected from a drop down form: and will be redirected to a "Details" page. Here is where the student information will be populated.). Any ideas into the proper way to do this would be greatly appreciated.
(I am currently thinking of adding a table to my sql and having it populated by Admin_ID as a FK student_ID as a FK, and AD_Select_ID Primary key )
i hope there is a more simple way. please advise.
thank you
Retrieve admin name
if(isset($_SESSION['username']) && isset($_SESSION['ad_loggedin'])) {
$q_auser = "SELECT fName FROM admins WHERE a_id = '$_SESSION[a_id]'";
$r_auser = mysqli_query($dbc, $q_auser);
$auser_data = mysqli_fetch_assoc($r_auser);
}
Retrieve user data
$q_users = "SELECT s_id, fName, lName, dob, email, gender, classification FROM students ORDER BY s_id ASC";
$r_users = mysqli_query($dbc, $q_users);
$user_data = mysqli_fetch_assoc($r_users);
Gather student ID & redirect to profile view
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['profile'])) {
#no profile selected
if($_POST['user'] == "0") {
header('Location: index.php');
} else {
$_SESSION['st_id'] = $_POST['user'];
header('Location: profile.php');
}
}
body post statement:
<label for="users"><h4>Select A User:</h4></label>
<select name="user" class="form-control" id="user" style="width:40%;">
<option value="0"> </option>
<?php
while ($user_data = mysqli_fetch_array($r_users)) {
echo '<option value="'.$user_data["id"].'">' .$user_data["s_id"]. " -> " .$user_data["lName"]. ", ".$user_data["fName"]. '</option>';
}
?>
</select>
<br />
<button type="submit" class="btn btn-primary" name="profile">View Profile</button>
You only ever need to have one session at a time. You can have that session store all the data, such as the actual user and the users being emulated. Whenever your PHP is trying to figure out who the user is, have it check the emulated user data as well. If you want more details, you'll need to give more details about your code.
I am trying to use a dynamic select form to send information to a MySQL database. The user will be able to choose their school, and then select their major from within that school's list (all retrieved from a MySQL table). I then want to send that information to a different table in the database to be stored.
This is what I have for the code thus far:
<select name="school">
<php
$sql = "SELECT school_name, school_id FROM school_table ORDER BY school_name";
$query = mysql_query($sql,$conn);
while($row = mysql_fetch_array($states))
{
echo ("<option value=$row[school_id]>$row[school_name]</option>");
}
?>
</select>
I don't know how to make the second select, which would ideally recognize the school_id from the first table and match it with the corresponding school_id on the second table, which also lists the majors at that school. Also, I don't know how to send the form when it is finally done to a MySQL table.
You could either use a simple form to submit the value from the combobox to the server (as HTTP POST or HTTP GET) and use the value as a variable in you SQL statement or you could use a simple AJAX request to send the necessary information to your php script. Anyway, your serverside code should look like this:
//process.php
$myRetrievedValue = $_POST["school"];
$mySqlStm = "SELECT * FROM foo WHERE bar = '".mysql_escape_string($myRetrivedValue)."'";
On the client side you code could look like this (using a simple form and no AJAX stuff):
<form action="process.php" method="post">
<select name="school">
<php $sql = "SELECT school_name, school_id FROM school_table ORDER BY school_name";
$query = mysql_query($sql,$conn); while($row = mysql_fetch_array($states)) {
echo ("<option value=$row[school_id]>$row[school_name]</option>"); } ?>
</select>
<input name="" type="submit" />
</form>
Please remember: Whenever you use a user input in you query use prepared statements (or at least escape methods as above) to avoid SQL injections.
answer is to select from both tables in one SELECT using joins:
http://dev.mysql.com/doc/refman/5.0/en/join.html
INNER JOIN
SELECT `school_table`.`school_name`,
`school_table`.`school_id`,
`2ndTable`.`school_id`,
`2ndTable`.`major`,
FROM school_table,2ndTable
WHERE `school_table`.`school_id`=`2ndtable`.`school_id`
ORDER BY school_name
or a
LEFT JOIN (returning all columns in the left)
SELECT `school_table`.`school_name`,
`school_table`.`school_id`,
`2ndTable`.`major`,
`2ndTable`.`school_id`
FROM school_table
LEFT JOIN on `school_table`.`school_id`=`2ndtable`.`school_id`
ORDER BY school_name
I have some trouble with this.
I have one database with the following tables:
Countries -> All countries of the world are added
Cities -> The cities are also added
user_profile -> The profile of the user with the fields "country" & "city".
Everything works fine, even the populating of the boxes is working. But I don't know how to get the SELECTED value of the user for both country & city.
I have the following code:
Select Country: <br />
<select id="countries">
<option value="">--</option>
<?php
$sql = "SELECT country, title FROM countries ORDER BY title ASC";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
echo "<option value=\"".$row['country']."\">".$row['title']."\n ";
}
?>
</select>
Select City: <br />
<select id="cities">
<option value="">Select one</option>
<?php
$sql = "SELECT country, title FROM cities ".
"ORDER BY title ASC";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
echo "<option class=\"".$row['country']."\" value=\"".$row['title']."\">".$row['title']."\n ";
}
?>
</select>
Now I need to check in the table user_profile which country & city he chose and show it to him.
I also use jchained (jquery plugin) to make both select boxes working together.
How can I achieve this? If I need to post anything else, please let me know.
Thanks in advance.
You have a lot of missing code here but I will try to help.
I am going to start by assuming that you have already stored the users selections in the user_profile table and that they are foreign keys to to correct relations.
To get the selected id's for repopulating the select boxes with the selected flag use:
SELECT country, city FROM user_profile where id = $user_id;
To get the text values you would do something like:
SELECT country.title as country, city.title FROM user_profile LEFT JOIN countries ON user_profile.country = country.id LEFT JOIN cities ON user_profile.city = cities.id WHERE user_profile.id = $user_id;
If you are not storing them as foreign key relations but instead by string title in the user_profile table you will need to do this:
SELECT country.title as country, city.title FROM user_profile LEFT JOIN countries ON user_profile.country = country.title LEFT JOIN cities ON user_profile.city = cities.title WHERE user_profile.id = $user_id;
You can then use these results to either display to the user or set the "SELECTED" flag in the options box.
Do you just mean you don't know what to do after they select the values? If so then you would just use the form to post the values to the new page. On the receiving page you can run a query to Update the user's profile.
Sorry if my response isn't detailed enough ><
edit Oh, I may see what you mean now. You're able to store it correctly but you want the correct option to be flagged as selected if it's what the user has previously set? If that's it then you can query for the value, then inside of the while loop just add a check to see if $user_country == $row['country'] and if so echo ' SELECTED '. Hope that helps!
I'm a sql noob trying to get this query to use 2 tables.
tables & columns are:
person:
department_id,
name,
etc...
department:
department_id,
dept_name,
etc...
I have a 'select' html form that the user will choose a dept_name from, and I need my php script to return every person with a matching department_id. Here is my code & query so far, I'd appeciate any help.
$search_dept = $_POST['search_dept'];
$conn = odbc_connect($odbc_name, $user_name, $pass_wd);
if ($conn) {
$query = "SELECT person.*
FROM department
JOIN person
ON department.department_id=person.department_id
WHERE department.name=$search_dept";
if($result = odbc_exec($conn, $query)) {
echo '..stuff';
while ($row = odbc_fetch_array($result)) {
...echo stuff
}
echo '...stuff';
}
else {
echo 'Query was unsuccessful';
}
}
else {
echo 'Unable to connect to database';
}
First of all, you are going about this the wrong way. You don't want to execute a WHERE clause against a text-type column if you can avoid it. Since your person table already has the department_id as a foreign key, you will want to use that value to do your selection. This means you will have to modify your select element to contain the department IDs as the options' values.
<!-- Example -->
<select name="dept_id">
<option value="1">Sales</option>
<option value="2">Support</option>
<option value="3">Fulfillment</option>
</select>
So now, not only will just the raw selection occur faster since you'll be executing against an indexed column (you did make it a proper FK so it's indexed, right?), but you will also be removing the join altogether! (which is another boost to the query's speed)
// Here is injection-safe code for the ODBC driver
$stmt = odbc_prepare( "SELECT * FROM person WHERE department_id = ?" );
$success = odbc_execute( $stmt, array( $_POST['dept_id'] ) );
// Here is the old, non-secure version, but is db-driver agnostic
$deptId = $_POST['dept_id']; // escape this please!
$query = "SELECT * FROM person WHERE department_id = $deptId";
Try this query, also make sure to escape any user input. What if the user would provide:
$_POST['search_dept']= "'; DROP TABLE person;";
Never ever ever thrust userinput!
$search_dept = mysql_escape_string($_POST['search_dept']); //make sure to escape this! you can use other functions for this as well. I'm not sure if PDO has some.
$query = "SELECT *
FROM person
JOIN department
ON department.department_id=person.department_id
WHERE department.name='$search_dept'";