How to allow NULL value on foreign key on php - php

Good day. I am seeking for help on what to do with the codes:
The PHP part:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$student = $_POST['student'];
$lecture = $_POST['lecture'];
$room = $_POST['room'];
$students = mysqli_query($con,"SELECT * FROM students WHERE student='$student'");
$lectures = mysqli_query($con,"SELECT * FROM lectures WHERE lecture='$lecture'");
$rooms = mysqli_query($con,"SELECT * FROM rooms WHERE room='$room'");
$student_row = mysqli_fetch_array($students);
$lecture_row = mysqli_fetch_array($lectures);
$room_row = mysqli_fetch_array($rooms);
What I want to do in this part is, if there is no entry on room input insert the value null in the room_id column in the reference table:
if($student != $student_row['student']) {
$addStudent = mysqli_query($con,"INSERT IGNORE INTO students (student) VALUES ('$student')");
$studentID = mysqli_insert_id($con);
}else{
$studentID = $student_row['student_id'];
};
if($lecture != $lecture_row['lecture']) {
$addLecture = mysqli_query($con,"INSERT IGNORE INTO lectures (lecture) VALUES ('$lecture')");
$lectureID = mysqli_insert_id($con);
}else{
$lectureID = $lecture_row['lecture_id'];
};
if($room != $room_row['room']) {
$addRoom = mysqli_query($con,"INSERT IGNORE INTO rooms (room) VALUES ('$room')");
$roomID = mysqli_insert_id($con);
}else{
$roomID = $room_row['room_id'];
};
I think this is the part that needs to be changed:
$addClass = mysqli_query($con,"INSERT INTO classes (student_id,lecture_id,room_id) VALUES ('$studentID','$lectureID','$roomID')");
if($addClass){
echo 'Success';
}else{
echo 'Error: '.mysqli_error($con);
};
};
?>
The HTML part:
<html>
<title>Add Class</title>
<body>
<form name="Add Class" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Student: <input type="text" name="student" />
</br></br>
Lecture: <input type="text" name="lecture" />
</br></br>
Room: <input type="text" name="room" />
</br></br>
<input type="submit" value="Add Class">
</form>
</body>
</html>
Thank you.

You can simply insert NULL as value. Like this:
if(empty($room))
$room = "NULL";
right before the mysqli insert. Make sure you actually pass the string null not empty or 0.
Oh and you obviously need to make sure the column is not marked as NOT NULL

Related

insert multiple same input fields php

Good day.
<input type="text" name="title">
<input type="text" name="name[]">
<input type="text" name="name[]">
<?php
if(isset($_POST['submit']){
$title = $_POST['title'];
$name = $_POST['name'];
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
}
?>
How can this code work? It should be inserted with same title and different names at the same time. Thank you.
Sample Form
I want the record to be updated as follows:
---------------------------------
|--bookID--|--Title--|--Author--|
|----1-----|---one---|----me----|
|----2-----|---two---|---you----|
---------------------------------
$_POST['name'] is an array with key 0,1 ...
So in your example you ve got:
//This is just an example
foreach($_POST['name'] as $name) {
}
Hope this helps.
Atul Vekariya example is correct but you need to also execute the query in the loop. That's why this example did not work for you.
if(is_array($_POST['name']) && !empty($_POST['name'])) {
foreach($_POST['name'] as $name) {
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
//execute query here. mysqli_query($add) or PDO::query
}
}
Please check below code
if(is_array($_POST['name']) && !empty($_POST['name'])) {
foreach($_POST['name'] as $name) {
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
//execute query here. mysqli_query($add) or PDO::query
}
}
After searching different solutions. Here is the one that works. Thank you for all the help.
<?php
include_once 'config/connect.php';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$title = $_POST['title'];
$name = $_POST['name'];
$length = count($name);
$addBook = "INSERT INTO books (title,name) VALUES ";
for($i=0; $i<$length; $i++){
$addBook .= "('$title','$name[$i]'),";
}
$addBook = rtrim($addBook, ',');
if($conn->query($addBook) === TRUE) {
echo "Success";
} else {
echo "Error: ".$addBook."<br>".$conn->error;
}
}
?>
<form action="addBook.php" method="POST">
Title: <input type="text" name="title">
<br/>
Authors: <input type="text" name="name[]"> <input type="text" name="name[]">
<br/>
<input type="submit" name="submit">
</form>

Trying to write to a mysql database but it keeps coming up empty set

For a school project I am trying to write to a table called enrolment where the student number and the course they have selected are added after they have been tested to make sure the student name and number exists in another database. No errors are coming up, however when I check my database afterward enrolment says its an empty set. Does anyone have suggestions?
<?php
require 'connect.php';
//making a variable from the user data
$name = $_POST["name"];
$number = $_POST["snumber"];
$course = $_POST["pcourse"];
//linking up the database
$link = mysqli_connect(HOST, USER, PASS, DB) or die (mysqli_connect_error());
// select all from table student which show student name and number
$squery = "SELECT * FROM student";
$sresult = mysqli_query($link, $squery);
$found = 0;
while ($srow = mysqli_fetch_array($sresult)) {
// testing if the student name and number match the users data
if ($name == $srow['family'] && $number == $srow['uid']) {
$enrol = "INSERT INTO enrolment (uid course) VALUES('$number' '$course')";
$found = 1;
break;
}
}
mysqli_close($link);
?>
<html>
<body>
<form action="index.php" method="post">
<br>
<input type = "submit" value="back" name="back">
</form>
</body>
</html>
index.php (form)
<!DOCTYPE html>
<html>
<body>
<h1>Course Selection</h1><br>
<form action="next.php" method="post">
Name: <input type="text" name="name" placeholder="Name" required="required" maxlength="50">
<br><br>
Student Number: <input type="text" name= "snumber" required="required" maxlength="9">
<br><br>
<?php
//form
require 'connect.php';
echo "Select a course: <select name = \"pcourse\">\n";
$link = mysqli_connect(HOST, USER, PASS, DB) or die(mysqli_connect_error());
$query = "SELECT * FROM course";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo "<option> $row[code] $row[name] $row[maxenroll]</option><br>";
}
mysqli_free_result($results);
mysqli_close ($link);
echo " </select>\n";
?>
<br><br>
<input type = "submit" value="submit" name= "submit">
</form>
</body>
</html>
Your insert code just a string. You should send to mysql your insert code. Try this
$enrol = "INSERT INTO enrolment (uid, course) VALUES($number, $course)";
$link->query($enrol);
My guess is that when checking the result set from student table - there is no such family and uid in it, which means - in the table. Instead of doing insert right away, try to display matching record from the database - if this is actually what you wanted to find. Then you can check what is actually stored in the database - and you can compare both.
Other thing is - why not limit select to exact that student?
Rebuild your query, something like:
$squery = "select * from student where family='".$name."' and uid='".$number."'".
Then you can check how many records were selected and display that number before doing any inserts.

Increment id on click in MySQL

I have a problem to visualize the solution for the problem that I have now.
The user is allowed to insert a row in a table.
And I try to display a button (input) +1 who allow the user to increment a column (vote) in a selected row among all created.
The problem is that I don't get the thing for rely incrementation to the desired id.
Here my code :
<form action="" method="post">
<input type="text" name="disease">name
<input name="mainsubmit" type="submit" value="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['mainsubmit']))
{
$nameDisease = $_POST['disease'];
$req = $db->prepare('INSERT into disease(name) VALUES(:name)');
$req->execute(array('name' => $nameDisease));
}
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch())
{
$id = $result['id'];
echo $id ?>
<form action="" method="post"> <input name="secondsubmit" type="submit" value="+1"> </form><?php
if(isset($_POST['secondsubmit']))
{
$db->exec("UPDATE disease SET vote = vote + 1 WHERE id = " .$id);
}
}
Logically, the code above doesn't work but I don't understand how find the solution.
In brief, i want to allow the user to increment a column in a selected row.
Thanks
Edit: Shadow, it's not my problem because your solution is used for automatically chose between INSERT or UPDATE if the line doesn't exist or exist. Me, I want allow the user to create rows and allow he to vote +1 on each of one that exist, and it will not be possible for he to insert a row from the input +1.
I created code snippet similar to your code style.
You have two submit buttons so you need to separate handling of those two requests.
The $id of the item you want to update in the second submit need's to come from hidden value in form.
In order for this to work you need to create table in mysql:
create table disease (id MEDIUMINT NOT NULL AUTO_INCREMENT, name VARCHAR(20), vote INTEGER, PRIMARY KEY (id)); - for example like this
<html>
<body>
<form action="" method="post">
<input type="text" name="disease">name
<input name="mainsubmit" type="submit" value="submit">
</form>
</body>
</html>
<?php
$db = new PDO('mysql:dbname=phpapp;host=db', 'root', 'phpapptest');
if (isset($_POST['mainsubmit'])) {
$nameDisease = $_POST['disease'];
$req = $db->prepare('INSERT into disease (name, vote) VALUES(:name, 0)');
$req->bindParam(':name', $nameDisease);
$req->execute();
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch()) { ?>
<form action="" method="post">
<p><?php echo $result['name'] . " : " . $result['vote'];?>
<input name="secondsubmit" type="submit" value="+1" />
<input type="hidden" name="id" value="<?php echo $result['id'];?>" />
</p>
</form>
<?php }
}
if (isset($_POST['secondsubmit'])) {
$req = $db->prepare("UPDATE disease SET vote = vote + 1 WHERE id = " . $_POST['id']);
$req->execute();
$query = $db->query('SELECT * FROM disease');
while ($result = $query->fetch()) {?>
<form action="" method="post">
<p><?php echo $result['name'] . " : " . $result['vote'];?>
<input name="secondsubmit" type="submit" value="+1" />
<input type="hidden" name="id" value="<?php echo $result['id'];?>" />
</p>
</form>
<?php }
}
?>

How to run SQL query on click using conditional PHP?

I am trying to create a room availability check page for a hostel and I am having an issue.
I have a database with a table named 'rooms' listing all type of rooms with these rows:
id [INT]
name (room type) [CHAR]
capacity (max capacity, not to be changed)[INT]
used (number of beds used, I want to change this dynamically!) [INT]
I created a code to generate the rooms list from the DB with PHP and I want the "+" and "-" buttons to either add or remove one unit in the used column for a specific room. How can I do this?
Here is my code:
<!-- SOME HTML/PHP THAT WORKS -->
<?php if ($roomlist->num_rows > 0) {
// output data of each row
while($room = $roomlist->fetch_assoc()) {
$roomid = $room["id"]; ?>
<div>
<!-- SOME OTHER HTML/PHP THAT WORKS -->
// THE ISSUE IS BELOW, IT SHOWS THE CORRECT AMOUNT BUT $room["used"] DOES NOT UPDATE
<div>
Used: <?php echo $room["used"] . " / " . $room["capacity"] ?>
</div>
<div>
<form action="" method="POST">
<input type="submit" name="remove" value="-" />
<input type="submit" name="add" value="+" />
<?php
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
?>
</form>
</div>
</div>
</div>
<?php }
} else {
echo "0 results";
} ?>
If you set the action of your form to whatever the name of your code is (e.g., "rooms.php"), then move
if(isset($_POST['remove'])){
$remove_query = mysqli_query("UPDATE rooms SET used = used - 1 WHERE id = $roomid") or die(mysqli_error());
} elseif (isset($_POST['add'])){
$add_query = mysqli_query("UPDATE rooms SET used = used + 1 WHERE id = $roomid") or die(mysqli_error());
}
up to the top so it updates the table before you query the table to fill in the rest of the page, it should work. Right now, your php is updating the table after the SELECT query to populate your page, so it doesn't appear to be updating.
I think a better tack would be implementing AJAX so your form updates the Used field without reloading the page.
Alright so I figured out a way on my own in the end so I post it here for other people facing a similar issue to overcome it ;)
Here is the concerned part of the code in index.php:
<form action="update.php?id=<?php echo $roomid ?>&action=remove&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="remove" class="minus" value="-" />
</form>
<form action="update.php?id=<?php echo $roomid ?>&action=add&used=<?php echo $room["used"] ?>&capacity=<?php echo $room["capacity"] ?>" method="post">
<input type="submit" name="add" class="plus" value="+" />
</form>
And the code of update.php:
if (isset($_REQUEST['used']) && isset($_REQUEST['id']) && isset($_REQUEST['capacity'])) {
$roomid = $_REQUEST['id'];
$used = $_REQUEST['used'];
$capacity = $_REQUEST['capacity'];
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add') {
if ($used >= $capacity) {
header("location: index.php");
} else {
$newValue = $used + 1;
$add_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'remove') {
if ($used <= 0) {
header("location: index.php");
} else {
$newValue = $used - 1;
$remove_query = mysqli_query($connection, "UPDATE `rooms` SET `used` = $newValue WHERE `ID` = $roomid") or die(mysqli_error());
header("location: index.php");
}
}
}

Show phpmyadmin cell in html textbox value

I have a database in phpmyadmin called fleet hire motors, and in that database is a table called customer.
In that table are columns called customerID and Surname. I have already done some coding on one page that lets the user select the customerID to edit the Surname.
On the next page I want a textbox. in that textbox, the default value should be what the current Surname is.
So, if i was to edit customer with customerID 1 (of which surname is currently Brown and I want to change to Green) the second page would show Surname: [Brown], where [] encloses a textbox.
I currently do not have any code, and would like to keep it primarily php. The first page is called editcustomer.php, and the second is called editcustomer2.php.
Any help is appreciated.
My current code is:
<html> <head> <title>Edit Customer</title> </head><body>
<?php mysql_connect("localhost","username","password") or die(mysql_error());
mysql_select_db("fleet hire motors") or die(mysql_error()); ?>
<?php
$CustomerID = $_GET["CustomerID"];
$query=mysql_query(" SELECT * FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
b$CustomerID = $row["CustomerID"];
} ?>
First Name: <input name="FirstName" type="text" value="
<?php
$FirstName = $_GET["CustomerID"];
include 'db.php';
$query=mysql_query(" SELECT FirstName FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
?> ">
<br> <input name="submitbtn" type="submit" value="Save"> <input name="resubmitbtn" type="submit" value="Reset"> </form> </body> </html>
Sorry for all the edits, as I am new to stackoverflow and just learning how to do it.
I have now updated my coding thanks to a response, but it is still not working. My most current coding is:
<html>
<head>
<title>Edit Customer</title>
</head>
<body>
<?php
mysql_connect("localhost","username","password") or die(mysql_error());
mysql_select_db("fleet hire motors") or die(mysql_error());
?>
<?php
$CustomerID = $_GET["CustomerID"];
$query=mysql_query(" SELECT * FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
$row = mysql_fetch_array($query);
if (!$row || !is_array($row)){
$CustomerID = 0;
$CustomerFirstName = '';
}
else {
$CustomerID = $row["CustomerID"];
$CustomerFirstName = $row['FirstName'];
}
?>
First Name: <input name="FirstName" type="text" value="<?php echo $CustomerFirstName; ? >">
<input name="submitbtn" type="submit" value="Save">
<input name="resubmitbtn" type="submit" value="Reset">
</form>
</body>
</html>
This does not give me anything in the textbox, and my submit button does not work.
You'll have to make an echo.
In case that your customerId shall be unique you did not need a while.
[...]
<?php
$CustomerID = $_GET["CustomerID"];
$query=mysql_query(" SELECT * FROM customer WHERE CustomerID = '$CustomerID' ") or die(mysql_error());
$row = mysql_fetch_array($query));
if (!$row || !is_array($row)){
$CustomerID = 0;
$CustomerFirstName = 'NoNameFound';
}
else {
$CustomerID = $row["CustomerID"];
$CustomerFirstName = $row['FirstName'];
}
//Debug
echo 'rowcontent: <pre>' . print_r($row, true) . '</pre>';
?>
First Name: <input name="FirstName" type="text" value="<?php
echo $CustomerFirstName;
?>">
[...]
You should also do some validation on your GET and POST before using them in your database e.g.
is_numeric($CustomerId)
or something like
[...] WHERE MD5(CustomerId) = ' . md5($CustomerId) . ' [...]

Categories