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) . ' [...]
Related
I've changed the code following people advices but my delete button doesn't work. The empID is a VARCHAR, not an INT
The way i wanted it to be done when i search a string of letters i would get a list of employees containing that string, then choose some checkboxes and when button is pressed they'd get deleted from the DB and the list of not chosen would still stay on that page.
Thanks in advance for any help!!!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Delete Record</title>
<link rel="stylesheet" href="style1.css" />
<style>dialog{margin-left:100px}
select { font-size:24px;}</style>
</head>
<body>
<div class="header">
<h2>List of the employees with the name entered</h2>
</div>
<form name="action_form" action="" method="post" />
<div class="input-group">
<input type="text" name="name" placeholder="Employee name" />
</div>
<button type="submit" class="btn" name="submit">SEARCH</button>
<?php
require('db.php');
$errors = array();
if(isset($_POST["name"])&&!empty($_POST["name"]))
{
$name=$_POST['name'];
$sqlResult=mysqli_query($con, "SELECT * FROM Employee WHERE empName LIKE '%$name%'");
if (mysqli_num_rows($sqlResult) > 0)
{
echo "<table>";
while($row=mysqli_fetch_assoc($sqlResult))
{
echo "<tr>";
echo "<td>"; ?><input type= 'checkbox' name='num[]' value='<?php echo $row['empID'] ?>'/><?php echo "</td>";
echo "<td>".$row['empID']."</td>";
echo "<td>".$row['empName']."</td>";
echo "<td>".$row['deptNo']."</td>";
echo "<td>".$row['addCounty']."</td>";
echo "<td>".$row['salary']."</td>";
echo "</tr>";
}
echo "</table>";
}
if(isset($_POST['delete'])&&(!empty($_POST['num'])))
{
$list = array();
$list = $_REQUEST['num'];
foreach($list as $delID)
{
$sqlResult = mysqli_query($con,"DELETE FROM employee WHERE empID LIKE '$delID'");
}
}
}
?>
<div class="input-group">
<label>Please choose the person from the list below</label>
</div>
<div class="input-group">
<button type="submit" class="btn" name="delete">FIRE SELECTED</button><br><br>
<button type="reset" class="btn" name="reset">RESET</button><br><br>
Back to the Menu
</div>
</form>
</body>
</html>
Try this :
if(isset($_POST["name"])&&!empty($_POST["name"]))
{
$name=$_POST['name'];
$sqlResult=mysqli_query($con, "SELECT * FROM Employee WHERE empName
LIKE '%$name%'")
}
The reason for the error (Undefined variable $name) is because you are only setting $name in your "if" statement when $_POST['name'] is set, but you are running the line:
$sqlResult = mysqli_query($con, "SELECT * FROM Employee WHERE empName LIKE '%$name%'");
every time the page is loaded. Because you have used $name in the SQL string, but it isn't always declared, you get the error.
I'm finding your code a little hard to read, but I think you probably just want to put the mysqli_query() line inside the "if" statement.
if(isset($_POST['name'] && !empty($_POST['name'])) {
$name = $_POST['name'];
$sqlResult = mysqli_query($con, "SELECT * FROM Employee WHERE empName LIKE '%$name%'");
}
Looks like you should wrap the $delId in "%"
So your delete query should look like this:
$sqlResult = mysqli_query($con,"DELETE FROM employee WHERE empID LIKE '%$delID%'")
Also bear in mind that the like statement will delete any row where the id is like any other id. You might consider changing this to:
$sqlResult = mysqli_query($con,"DELETE FROM employee WHERE empID = '$delID' ")
Another thing to keep in mind is that you should consider using parameterized queries to prevent sql injection. Read thise for more details:
What is parameterized query?
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
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.
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 }
}
?>
So I'm just making a simple program that puts names into a database. I got that part down, I can enter a name into a form, then display it on the page, but now I'd like to know how to delete them from the database, and no longer show them on the page.
I added a button next to each name that triggers the third if statement (with the commented out query), and from what I can tell it's best to run a query based on the element's id (my primary key that auto increments), but I have no idea how to get the id from the element who's button I'm clicking on.
How do I get the id from one of the elements in my while loop? Or if there's a better way to delete them, what's that?
if (mysqli_connect_errno()) {
die('could not connect');
}
if (isset($_POST['first_name'], $_POST['last_name'])){
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$putitin = mysqli_query($db, "INSERT INTO names (first_name, last_name) VALUES ('$first_name', '$last_name')");
}
if (isset($_POST['del'])){
//$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = ");
}
?>
<html>
<head>
</head>
<body>
<form action='' method='post'>
<div>
<label for "first_name">First name</label>
<input type="text" name="first_name">
</div>
<div>
<label for "last_name">Last name</label>
<input type="text" name="last_name">
</div>
<div>
<input type="submit" value="Insert">
</div>
</form>
<hr>
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo "<form action='' method='post'><p>Name: $fname $lname $id<input type='submit' name='del'></form></p>";
}
} else {
echo 'No results';
}
?>
</body>
</html>
This is one way.
change your html part to
<form action='' method='post'>
<input type='hidden' name='id' value='$id' />
<p>Name: $fname $lname $id
<input type='submit' name='del' value=''>
</form></p>
and your php
if (isset($_POST['del'])){
$id = $_POST['id'];
$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = '$id'");
}
Note:
What you can do is to put all your input fields inside your while loop. Then assign values to each of them, but we have to use array to store them accordingly.
We can use checkbox to store the IDs.
What will happen, is user can select from the list of names they wanted to delete by ticking the corresponding checkbox, then pressing the Delete button below.
Your code
<form action="" method="POST">
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo '<input type="checkbox" name="id[]" value="'.$id.'">'.$fname.' '.$lname.'<br>';
} /* END OF WHILE LOOP */
?>
<input type="submit" value="Delete" name="delete">
</form>
And your PHP that will process the form:
<?php
if(isset($_POST["delete"])){
$counter = count($_POST["id"]);
for($x = 0; $x<$counter; $x++){
if(!empty($_POST["id"][$x])){ /* CHECK IF AN ITEM IS SELECTED */
/* DELETE QUERY */
if($stmt = $db->prepare("DELETE FROM names WHERE id = ?")){
$stmt->bind_param("i",$_POST["id"][$x]);
$stmt->execute();
$stmt->close();
} /* END OF PREPARED STATEMENT */
} /* END OF IF; CHECKING IF IT IS SELECTED */
} /* END OF FOR LOOP */
} /* END OF ISSET DELETE */
?>