How to select corresponding ID in sql - php

I am new to php and I am trying to make a school portal, and right now I am trying to create the page where admins can make the classes.
All I need to know how to do is allow the admin to select a teacher (names or username come directly from database) from the drop down menu, and enter the corresponding ID into my 'class' table, in teacher_id.
$query = "SELECT Username FROM tbluser WHERE Role='Teacher'";
$result2= mysqli_query($conn, $query);
<body>
<form action="createclass.php" method="POST">
<div>
<label>Class name</label>
<input type="text" name="classname" class="form-control" placeholder="Enter new username">
<br/>
<label>Teacher</label>
<select name ="teacher">
<option selected = "true" disabled="disabled"> Select one from below...</option>
<?php
while ($rows=mysqli_fetch_assoc($result2))
{
$teachername= $rows['Username'];
echo"<option value ='$teachername'>$teachername</option>";
}
?>
</select>
if(isset($_POST["btnAddclass"])){
$classname = $_POST["classname"];
$teacher = $_POST["teacher"];
$subject = $_POST["subject"];
$section = $_POST["section"];
$yeargroup = $_POST["yeargroup"];
$result1 = mysqli_query($conn, "SELECT ID FROM teacher INNER JOIN tbluser ON tbluser.ID=teacher.tbluser_ID WHERE Username = '$teacher'"); // using mysqli_query instead
$sql = "INSERT INTO class (classname, teacher_id, yeargroup_id, subject_id, section_id) VALUES ('$classname', '$result1', '$subject','$section','$yeargroup')";
if(!mysqli_query($conn,$sql))
{
echo "Error";
}
else
{
echo "New class has been added.";
}
}
database

Also select ID from tbluser, this ID is a teacher ID:
$query = "SELECT ID, Username FROM tbluser WHERE Role='Teacher'";
$result2= mysqli_query($conn, $query);
<form action="createclass.php" method="POST">
<div>
<label>Class name</label>
<input type="text" name="classname" class="form-control" placeholder="Enter new username">
<label>Teacher</label>
<select name="teacher">
<option selected="true" disabled="disabled"> Select one from below...</option>
<?php
while ($rows=mysqli_fetch_assoc($result2)) {?>
<option value="<?php echo $rows['ID']?>"><?php echo $rows['Username']?></option>
<?php
}?>
</select>
On submit:
$classname = $_POST["classname"];
$teacherID = $_POST["teacher"];
$subject = $_POST["subject"];
$section = $_POST["section"];
$yeargroup = $_POST["yeargroup"];
$sql = "INSERT INTO class (classname, teacher_id, yeargroup_id, subject_id, section_id) VALUES ('$classname', '$teacherID', '$subject','$section','$yeargroup')";
And as you use unsafe data from user input, consider moving to prepared statements to avoid SQL injections.

Related

How to Save select option value data instead of Id using PHP MYSQL

How best can I save a select option value name instead of the id using just Ajax, PHP and MYSQL.
I tried many ways but for now when I select the data and store back it keeps saving generated id and that's not what I want.
When i decided to change the id of the selection option to value i the values does show on the drop down.
Details.php
<form method="post" name="signup" onSubmit="return valid();">
<label class="control-label">Profile ID</label>
<select id="employee" name="regcode" class="form-control">
<option value="" selected="selected">Select Profile ID</option>
<?php
$sql = "SELECT id,regcode FROM tbstudentprofile";
$query = $dbh->prepare($sql);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
?>
<option name="regcode" value="<?php echo $row["id"]; ?>">
<?php echo $row["regcode"]; ?> </option>
<?php } ?>
</select>
<div class=" form-group1 form-last>
<label class=" control-label">Status</label>
<textarea name="status" row="2"></textarea>
</div>
<button type="submit" name="save">Save </button>
</form>
enter code here
query
if (isset($_POST['save'])) {
$regcode = $_POST['regcode'];
$status = $_POST['status'];
$sql = "INSERT INTO studentschooltbl(regcode,status) VALUES(:regcode,:status)";
$query = $dbh->prepare($sql);
$query->bindParam(':regcode', $regcode, PDO::PARAM_STR);
$query->bindParam(':status', $status, PDO::PARAM_STR);
$query->execute();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$lastInsertId = $dbh->lastInsertId();
if ($lastInsertId) {
$msg = " Registration successfully";
} else {
$error = "error";
}
}

not able to get values from database and updating values to the database

into schooling entry form, I am not able to get value of employee_id from post.
I did Print_r for $employee_id, blank output is rendered.
Also if allocated static value to $employee_id, $sum contains only value posted through the form, instead it should show the value from input form plus value from existing value available in database.
<?php
$get = db_query("SELECT field_employee_id_value FROM field_data_field_employee_id ORDER BY field_employee_id_value ASC");
$getempnames = db_query("SELECT field_employee_id_value FROM field_data_field_employee_id ORDER BY field_employee_id_value ASC");
if(isset($_POST['apply'])){
$sql = db_query("SELECT COUNT(id) as count_id FROM schooling WHERE employee_id = '$_POST[employee_id]' AND claim_year = '$_POST[claim_year]'");
$row = $sql->fetchAssoc();
if('1' == $row['count_id']){
$sqlupdate = db_query("UPDATE schooling SET limit_amount = '".$_POST['limit_amount']."' WHERE employee_id = '$_POST[employee_id]'");
echo "Schooling limit updated to user ";
} elseif ('0' == $row['count_id']){
$sqlinsrt = db_query("INSERT INTO schooling (employee_id, limit_amount, claim_year) VALUES ('".$_POST["employee_id"]."','".$_POST["limit_amount"]."','".$_POST["claim_year"]."')" );
echo "Schooling limit applied to user";
} else{
echo "Already Applied schooling limit";
}
}
if(isset($_POST['save'])){
$employee_id = $_POST['employee_id'];
$claim_amount = $_POST['claim_amount'];
$claim_year = $_POST['claim_year'];
$sqlchkemp = db_query("SELECT COUNT(id) as count_id FROM schooling WHERE employee_id = '$employee_id' AND claim_year = '$claim_year'");
$empavailable = $sqlchkemp->fetchAssoc();
if('1' == $empavailable['count_id']){
$getlimit = db_query("SELECT limit_amount FROM schooling WHERE employee_id = '$employee_id' AND claim_year = '$claim_year'");
$limit = $getlimit->fetchAssoc();
$getemptotalclaim = db_query("SELECT claim_amount FROM schooling
WHERE employee_id = '$employee_id' AND claim_year = '$claim_year'");
$emptotalclaim = $getemptotalclaim->fetchAssoc();
$totalclaimed = array_sum($emptotalclaim);
$availability = $limit['limit_amount'] - $_POST['claim_amount'];
$sum = $totalclaimed['claim_amount'] + $claim_amount;
if ($sum <= $limit['limit_amount']){
$sqlinsert = db_query("UPDATE schooling SET claim_amount = '$sum' WHERE employee_id = '$employee_id'");
echo "values updated successfuly";
}
else{
echo "limit is over, you can avail total amount ".$availability." as per ".$limit['limit_amount']." alloted";
}
}
else{
echo "employee schoolig limit is not set";
}
}
?>
<html>
<body>
<form id='applylimit' action='' method='post' accept-charset='UTF-8'>
<fieldset>
<label>Apply Schooling Limit amount to Employee</label>
<label for='employee_id'>Employee Id</label>
<select name='employee_id'>
<option value="0">Please Select</option>
<?php
while($row = $getempnames->fetchAssoc())
{
?>
<option value = "<?php echo($row['field_employee_id_value'])?>">
<?php echo($row['field_employee_id_value']) ?>
</option>
<?php
}
?>
</select>
<label for='limit_amount'>Limit Amount</label>
<input type='number' name='limit_amount' id='limit_amount' maxlength="50" />
<label for='claim_year'>Claim Year</label>
<select type='number' name='claim_year' id='claim_year' maxlength="50">
<option value="2018-19">2018-19</option>
<option value="2019-20">2019-20</option>
</select>
<button type="submit" name="apply">Apply</button>
</fieldset>
</form>
<form id='schoolingentry' action='' method='post' accept-charset='UTF-8'>
<fieldset>
<label for='employee_id'>Employee Id </label>
<select name='employee_id'>
<option value="0">Please Select</option>
<?php
while($rowemp = $get->fetchAssoc())
{
?>
<option value = "<?php echo($row['field_employee_id_value'])?>" >
<?php echo($rowemp['field_employee_id_value']) ?>
</option>
<?php
}
?>
</select>
<label for='claim_amount'>Claim Amount</label>
<input type='number' name='claim_amount' id='claim_amount' maxlength="50" />
<label for='claim_year'>Claim Year</label>
<select name='claim_year' id='claim_year' maxlength="50">
<option value = "2018-19">2018-19</option>
<option value = "2019-20">2019-20</option>
</select>
<button type="submit" name="save">save</button>
</fieldset>
</form>
</body>
</html>
word of warning, do not put anything submitted from a $_POST straight into a database query. You should sanitize it all by passing in the parameters.
e.g.
$result = db_query('SELECT n.name FROM users n WHERE n.name = :name', array(':name' => $name));
If the first query isn't returning any results, it's likely those two parameters you are passing into the string are not what you expect, or not valid. Try echoing out the two variables, then running the SQL query manually.
Or if you want Drupal to be a bit more verbose, wrap it in a exception catcher..
e.g.
catch (\PDOException $e) {
$error = $e->getMessage();

How To Insert Many To Many Tabel Auto Increment

A B C
------- --------- ------------
id_A* id_B* id_C*
name id_A** name
address id_C**
I created a table as in the example above I've tried to do input in Table A, B then C, but what if I want to do the input of C then the input table B in conjunction with Table A, all tables in the auto increment primary key
<input type="text" name="id_A" />
<input type="text" name="id_B" />
<input type="text" name="name" />
<input type="text" name="address" />
<select class="form-control" name="id_C">
<?php
$query = "select * from C";
$r = mysql_query($query);
while ($row=mysql_fetch_array($r)) {
?>
<option value="<?php echo $row['id_C'];?>" name="id_C"><?php echo $row['name'];?></option>
<?php
}
?>
</select>
And Then
isset($_POST['submit'])) {
$id_A = $_POST['id_A'];
$name = $_POST['name'];
$address = $_POST['address'];
$q = "insert into A (id_A,name,address) VALUES('$id_A','$name','$address')";
$dq = mysql_query($q);
$id_B = $_POST['id_B'];
$query = mysql_query("insert into B(id_b,id_A,id_C) values('$id_b', '$id_A' ,'$id_C')");
please help me,
i' am a realy2 confuse

How can i convert a name to id

I am trying update an id that has a foreign key to another table of names. I have a drop menu and in the drop menu I have name from table NAME_TEST. I need to select the name but the insert that I want is:
INSERT INTO (test) values (the value that i need is the ID of selected name)
Code:
<html> <h1>Update form</h1></html>
<?php
if (isset($_POST['submit'])) {
$connect = mysqli_connect('localhost', 'root', '', 'test');
$query = "UPDATE test SET location_name='".$_POST['new_location']."' WHERE id='".$_POST['location']."' LIMIT 1";
$res = mysqli_query($connect, $query);
if (!$res) {
die("Something went wrong");
}
}
// This is the code to load the select options
$connect = mysqli_connect('localhost', 'root', '', 'test');
$query = 'SELECT * FROM name_test';
$res = mysqli_query($connect, $query);
echo "Choose setup";
$options = array();
while($row = mysqli_fetch_assoc($res)) {
$options[] = $row;
}
?>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>"><BR><BR>
<select name="location">
<option value="0">--- Select an option ---</option>
<?php foreach ($options as $option): ?>
<option value="<?= $option['id'] ?>"><?= $option['name'] ?></option>
<?php endforeach; ?>
</select><br /><BR><BR>
<B> New name:</B> <BR> <input type="text" name="new_location"><br /><BR><BR>
<input type="submit" name="submit" value="Update" />
</form>
You can use a join for this. The idea is something like this:
INSERT INTO t(nameid)
select nameid
from names n
where n.name = ?;
t is the table you want to insert into. names is the table that has the name id and the name.

why doesn't it want to add a post or category?

As a school assignment I need to make a cms, in that I need to be able to make post edit them and delete them. so for i can edit and delete them, but for some reason I cant get it to insert the post(and also the categories, same almost the same) I hope you guys can help me.
Here is the code:
The form
<form action="includes/doAddpost.php" method="post">
<label for="PostName">Name</label>
<input type="text" name="PostName" id="PostName" placeholder="Title" autofocus="auto"/>
<label for="PostAuthor">Author</label>
<input type="text" name="PostAuthor" id="PostAuthor" placeholder="Authors name"
value="<?php if (isset($_SESSION['username'])) {
echo $_SESSION['username'];
}
?>"/>
<label for="PostContent">Content</label>
<textarea name="PostContent" id="PostContent" placeholder="content"></textarea>
<label for="PostCats">category</label>
<select name="PostCats">
<?php
$query = "SELECT * FROM categories";
$result = mysqli_query($mysqli, $query);
while ($cat = mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $cat['id']; ?>"><<?php echo $cat['title']; ?></option>
<?php } ?>
and this part doesnt seem to work either
</select>
<input type="submit" name="submit" value="submit"/>
</form>
Here is the doAddpost page:
<?php
include '../../includes/functions.php';
sec_session_start();
if(isset($_POST['submit'])){
if(isset($_POST['PostName'])){
if(isset($_POST['PostContent'])){
addPost($mysqli,$_POST['PostName'],$_POST['PostAuthor'], $_POST['PostContent'],$_POST['PostCats']);
header("Location: ../posts.php");
}else{
echo"please enter some content!";
}
} else{
echo"please set a category name!";
include('../addpost.php');
}
}else{
header("Location: ../addpost.php");
}
?>
and the function:
function addPost($mysqli, $pName, $pAuthor, $pContent, $pCat = 1)
{
$query = "INSERT INTO posts VALUES ('$pName', '$pAuthor', '$pContent', $pCat)";
mysqli_query($mysqli, $query);
}
Can anyone tell me what is the issue I am facing ?
Just edit your function as ,
function addPost($mysqli, $pName, $pAuthor, $pContent, $pCat = 1)
{
$query = "INSERT INTO posts (`your_column1`, `your_column_2`, `your_column_3`, `your_column_4`) VALUES ('$pName', '$pAuthor', '$pContent', $pCat)";
mysqli_query($mysqli, $query) or die(mysqli_error());
}
and then try...
Also in you select list change it as,
<option value="<?php echo $cat['id']; ?>"><?php echo $cat['title']; ?></option>
You placed an extra < there in your code..check that...:)
Now its time to step by step debugging:-
1) change your select category mysqli_query as below for debugging purpose
mysqli_query( $mysqli , $query ) or trigger_error($mysqli->error."($query)");
2) for you insert query mention column name in which you want to insert record . as you mentioned in comment you dont want id null so you should make you id column as AUTOINCREMENT
e.g
INSERT INTO posts (`column1`,`column2`,`column3`,`column4`) VALUES ('$pName', '$pAuthor', '$pContent', $pCat);

Categories