PHP Insert Into function only working once? - php

I'm trying to write some PHP code that adds data submitted via a form into a database table I have created. It works great - once. Once I have submitted data and added it to the database via the form once already it will no longer work. I'm thinking it's a problem with the function I have written as when using var_dump(); on the variables I'm submitting in the form they all come out fine.
I'd appreciate any suggestions you guys might have, thanks!
<form action="" method="post">
<label for="habbo_name"><center><b>Habbo Name:</b></label><br >
<input type="text" name="habbo_name" size="30">
<b><center>Transfer Status:<br ><select name="transfer_status">
<option value="Stage Five">Stage Four - Rejected</option>
<option value="Stage Four">Stage Four - Accepted</option>
<option value="Stage Three">Stage Three</option>
<option value="Stage Two">Stage Two</option>
<option value="Stage One" selected="selected">Stage One</option>
</select>
<label for="date"><center><b>Date:</b></label><br >
<input type="text" name="date" size="30"><br />
<input type="Submit"><br /><br />
</form>
Go back
<?php
if (empty($_POST) === false) {
$habbo_name = $_POST['habbo_name'];
$transfer_status = $_POST['transfer_status'];
$date = $_POST['date'];
add_transfer($habbo_name, $transfer_status, $date);
header('Location: moderate.php');
exit();
}
?>
Function:
function add_transfer($habbo_name, $transfer_status, $date) {
global $con;
$query = "INSERT INTO `transfers` SET `habbo_name`='$habbo_name', `transfer_status`='$transfer_status', `date`='$date'";
$update = $con->prepare($query);
$update->execute();
}

You have syntax error in insert query, use it like below
$query = "INSERT INTO `transfers` (`habbo_name`,`transfer_status`,`date`) VALUES ('$habbo_name', '$transfer_status', '$date')";

Related

Having trouble storing html form resources into mySQL using mysqli method alongside file function

PHP that is run before the form
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
include 'config.php';
include 'pageblocks.php';
include 'functions.php';
if ( isset( $_POST ) && ! empty( $_FILES ) ) {
echo upload_file();
echo '1';
$stmt = $conn->prepare("INSERT INTO art_content (headline, content_type, postdate, title,
content, index_thumb) VALUES (?,?,?,?,?,?)");
echo '2';
$stmt->bind_param('ssssss', $_POST['headline'],
$_POST['content_type'], $_POST['postdate'], $_POST['title'], $_POST['content'],
$_POST['file']);
echo '3';
$stmt->execute();
echo '4';
$conn->close();
unset($_POST);
}
metablock('content upload page');
headerblock('');
?>
The form that I'm trying to implement on site
<form method ="post" action="" enctype="multipart/form-data">
<label for="headline"><strong>Choose Index Headline</strong></label><br><br>
<select name="headline">
<option value="addition to gallery">addition to gallery</option>
<option value="new patron content">new patron content</option>
<option value="new youtube video">new youtube video</option>
<option value="new addition to articles">new addition to articles</option>
</select><br><br>
<label for="content_type"><strong>Choose content type:</strong></label><br><br>
<select name="content_type">
<option value="digital photograph">digital photograph</option>
<option value="digital painting">digital painting</option>
<option value="traditional painting">traditional painting</option>
<option value="twitch branding">twitch branding</option>
<option value="article">article</option>
</select><br><br>
<label><strong>post date</strong></label><br><br>
<input name="postdate" type="text"><br><br>
<label><strong>title</strong></label><br><br>
<input name="title" type="text"><br><br>
<label><strong>text content</strong></label><br><br>
<textarea name="content" type="text"></textarea><br><br>
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
My upload file function works fine but MySQL data doesn't seem to make it to server.
I can't figure out what to do, thinking about trying the PDO method cause it seems less confusing but feels bad giving up on mysqli method to connect

Updating specific data in MySql table through form

I am making a online application used for storing user data and order information. I have successfully managed to create a system to which you first add customers and then add orders to specific customers.
I now want to create a function that would let the administrator of the page edit a certain line in the table.
I managed to figure out how to manually change it through a MySql code but I cannot figure out how to change it through a form? Right now I have this, but I do not think this is the correct way to do it... It works, but is very limited. For example, I am not sure what to do, if admin selects date?
PHP AND HTML
<?php
$id = $_GET['id'];
?>
<form action="update.php" method="POST" >
<input type="text" name="id" style="display:none;" value="<?php echo $id; ?> placeholder="Hidden id">
</select>
<select name="change"style="width:32.9%;" required>
<option selected hidden value="">Select a entry you want to edit</option>
<option value="narocnik">Customer</option>
<option value="naslov">Adress</option>
<option value="kraj">City</option>
<option value="enaslov">E-mail</option>
<option value="telefon">Number</option>
<option value="datumzacetka">Start date</option>
<option value="datumkonca">due date</option>
<option value="material">Material</option>
</select>
<input type="text" name="new" style="width:32.5%;" placeholder="New entry">
<input type="submit" value="PoĊĦlji">
</form>
AND THE MYSQL PART
<?php
include 'baza.php';
$change = $_POST['change'];
$new = $_POST['new'];
$id = $_GET['id'];
$id = $_POST['id'];
$sql = "UPDATE projekti SET $change='$new' where id='$id'";
if ($conn->query($sql) === TRUE) {
header("Location: projekti.php?id=$id");
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
As I said, the function works, but it is far from perfect, so any suggestions would be very welcome :) The most important thing would be the ability to have all the fields displayed but only update the newly inputted ones.

Booking system with php and mysql

So I'm producing this booking system for supplementary lessons in school,and I'm new to coding.So I'm experiencing many problems when making this.
I'm using PHP and mysql for my system.The following is my tedious 100-line-code for 'sinsert.php'
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Booking Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
//Prevent empty fields
$date = $room = $tid = $subj = $start = $end = $noofstu = null;
$nodate = $noroom = $notid = $nosubj = $nostart = $noend = $nonoofstu = null;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["date"])) {
$nodate = "*Date of lesson is required";
$date = null;
} else {
$date = $_POST["date"];
}
if (empty($_POST["room"])) {
$noroom = "*Room is required";
$room = null;
} else {
$room = $_POST["room"];}
if (empty($_POST["tid"])) {
$notid = "*Teacher in charge is required";
$tid = null;
} else {
$tid = $_POST["tid"];}
if (empty($_POST["noofstu"])) {
$nonoofstu = "*Number of Students Attending is required";
$noofstu = null;
} else {
$noofstu = $_POST["noofstu"];}
}
function ($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;}
?>
<div id='frm'><form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<p><h1><u>Lesson Booking Form</u></h1></p>
<p>
<label>Date of Lesson:</label>
<input type="date" name="date" >
<br><span class="error"><?php echo $nodate;?></span>
</p>
<p>
<label>Room:</label><br>
<input type="radio" name="room" value="246"/> Room 246
<input type="radio" name="room" value="340"/> Room 340
<input type="radio" name="room" value="342"/> Room 342<br>
<span class="error"> <?php echo $noroom;?></span>
</p>
<p>
<label>Teacher in charge:</label><br>
<input type="radio" name="tid" value="T001"/>Mr.Williams
<input type="radio" name="tid" value="T002"/>Mr.Zimmerman
<input type="radio" name="tid" value="T003"/>Ms.Alcott<br>
<span class="error"> <?php echo $notid;?></span>
</p>
<p>
<label>Subject:</label>
<select name="subj">
<option value="unitA">Unit A</option>
<option value="unitB">Unit B</option>
<option value="unitC">Unit C</option>
<option value="unitD">Unit D</option>
<option value="unitE">Unit E</option>
<option value="unitF">Unit F</option>
</select>
</p>
<p>
<label>Starting Time:</label>
<select name="start">
<option value='09:00:00'>09:00</option>
<option value='10:00:00'>10:00</option>
<option value='11:00:00'>11:00</option>
<option value='12:00:00'>12:00</option>
<option value='13:00:00'>13:00</option>
<option value='14:00:00'>14:00</option>
<option value='15:00:00'>15:00</option>
<option value='16:00:00'>16:00</option>
<option value='17:00:00'>17:00</option>
</select>
<label>Ending Time:</label>
<select name="end">
<option value='10:00:00'>10:00</option>
<option value='11:00:00'>11:00</option>
<option value='12:00:00'>12:00</option>
<option value='13:00:00'>13:00</option>
<option value='14:00:00'>14:00</option>
<option value='15:00:00'>15:00</option>
<option value='16:00:00'>16:00</option>
<option value='17:00:00'>17:00</option>
<option value='18:00:00'>18:00</option>
</select>
</p>
<p>
<label>Number of Students Attending:</label>
<input type='number' name='noofstu' min='1'max='40'><br>
<span class="error"><?php echo $nonoofstu;?></span>
</p>
<p>
<input type="reset" id="reset" value="Reset">
<input type="submit" id="submit" value="Submit">
</p>
</form>
<?php
//Insert data in mysql database
$date = $_POST['date'];
$room = $_POST['room'];
$tid = $_POST['tid'];
$subj = $_POST['subj'];
$start = $_POST['start'];
$end = $_POST['end'];
$noofstu = $_POST['noofstu'];
$conn = #mysqli_connect("localhost","root","","sba");
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "INSERT INTO booking (date, room, tid, subj, start, end, noofstu) Values (?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($sql);
$stmt->bind_param( $_POST['date'], $_POST['room'], $_POST['tid'], $_POST['subj'], $_POST['start'], $_POST['end'], $_POST['noofstu']);
$stmt->execute();
if(!mysqli_query($conn, $sql))
{
echo "Not Inserted!";
}
else
{
echo "Inserted";
}
$conn->close();
?>
</div>
</body>
There are two codes in 'sinsert.php'.The first code is to make sure the user filled in all fields before submitting or else error codes will appear.The first code is mostly copied from W3schools.So I don't think there will be any problems regarding this code.
The second code is to insert the inputted data into the 'booking' table in the 'sba' database.I made code with the help of my teacher's code and PHP: Inserting Values from the Form into MySQL
The 'booking' table consists of 8 fields.Besides the 7 fields mentioned in the code,there's also primary key field 'bookid' which is in auto increment
Here are the problems I encountered
1.Everytime I went to the 'sinsert.php' page,I got 2 warning messages beneath my form
The first warning message states: 'mysqli_prepare() expects exactly 2 parameters, 1 given in on line 143'
The other is fatal error message that states: 'Uncaught Error: Call to a member function bind_param() on null in sinsert.php:144 Stack trace: #0 {main} thrown in sinsert.php on line 144'
And I have no idea what they mean or how to solve them
2.I also cannot insert the inputted data in the database.My guess is due to the error messages above.But I don't actually know the real reason
I'd like to know how can I solve the above problems.I'm really grateful if you helped
Bonus Question:How can I prevent double booking,like no records should have the same room and same time
Your main issue is you are running the DB stuff even if the form is not submitted. The PHP code at the bottom.
I cleaned it all up for you:
<?php
if(!empty($_POST)){
$errors = [];
$date = empty($_POST["date"]) ? false : (new DateTime($_POST["date"]))->format('Y-m-d');
if(!$date) $errors["date"] = "*Please set a Date of the lesson";
$room = empty($_POST["room"]) ? false : $_POST["room"];
if(!$room) $errors["room"] = "*Please pick a room";
$tid = empty($_POST["tid"]) ? false : $_POST["tid"];
if(!$tid) $errors["tid"] = "*Please pick a Teacher";
$noofstu = empty($_POST["noofstu"]) ? false : trim($_POST["noofstu"]);
if(!$noofstu) $errors["noofstu"] = "*Please set the number of students that are attending";
$start = $_POST["start"];
$end = $_POST["end"];
$subj = $_POST['subj'];
if(empty($errors)){
$conn = mysqli_connect("localhost","root","","sba");
if(mysqli_connect_errno()) die("Failed to connect to MySQL: " . mysqli_connect_error());
$sql = "INSERT INTO booking (date, room, tid, subj, start, end, noofstu) Values (?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($sql);
$stmt->bind_param( $date, $room, $tid, $subj, $start, $end, $noofstu);
$stmt->execute();
if(!mysqli_query($conn, $sql)) $errors["DB"] = "Dateabase error!";
}
}
?>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
<title>Booking Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id='frm'>
<form action="" method="post" >
<p>
<h1><u>Lesson Booking Form</u></h1>
<span class="error"><?php echo isset($errors['DB']) ? $errors['DB'] : '';?></span>
</p>
<p>
<label>Date of Lesson:</label>
<input type="date" name="date" >
<br><span class="error"><?php echo isset($errors['date']) ? $errors['date'] : '';?></span>
</p>
<p>
<label>Room:</label><br>
<input type="radio" name="room" value="246"/> Room 246
<input type="radio" name="room" value="340"/> Room 340
<input type="radio" name="room" value="342"/> Room 342<br>
<span class="error"><?php echo isset($errors['room']) ? $errors['room'] : '';?></span>
</p>
<p>
<label>Teacher in charge:</label><br>
<input type="radio" name="tid" value="T001"/>Mr.Williams
<input type="radio" name="tid" value="T002"/>Mr.Zimmerman
<input type="radio" name="tid" value="T003"/>Ms.Alcott<br>
<span class="error"><?php echo isset($errors['tid']) ? $errors['tid'] : '';?></span>
</p>
<p>
<label>Subject:</label>
<select name="subj">
<option value="unitA">Unit A</option>
<option value="unitB">Unit B</option>
<option value="unitC">Unit C</option>
<option value="unitD">Unit D</option>
<option value="unitE">Unit E</option>
<option value="unitF">Unit F</option>
</select>
</p>
<p>
<label>Starting Time:</label>
<select name="start" style="margin-right:15px" >
<option value="09:00:00">09:00</option>
<option value="10:00:00">10:00</option>
<option value="11:00:00">11:00</option>
<option value="12:00:00">12:00</option>
<option value="13:00:00">13:00</option>
<option value="14:00:00">14:00</option>
<option value="15:00:00">15:00</option>
<option value="16:00:00">16:00</option>
<option value="17:00:00">17:00</option>
</select>
<label>Ending Time:</label>
<select name="end">
<option value="10:00:00">10:00</option>
<option value="11:00:00">11:00</option>
<option value="12:00:00">12:00</option>
<option value="13:00:00">13:00</option>
<option value="14:00:00">14:00</option>
<option value="15:00:00">15:00</option>
<option value="16:00:00">16:00</option>
<option value="17:00:00">17:00</option>
<option value="18:00:00">18:00</option>
</select>
</p>
<p>
<label>Number of Students Attending:</label>
<input type="number" name="noofstu" min="1" max="40"><br>
<span class="error"><?php echo isset($errors['noofstu']) ? $errors['noofstu'] : '';?></span>
</p>
<p>
<input type="reset" id="reset" value="Reset">
<input type="submit" id="submit" value="Submit">
</p>
</form>
</div>
</body>
</html>
There is too much really to cover, but the (condition) ? true : false; style is called a ternary statement. In PHP7 some of these could be replace with null coalesce operator ?? For example this:
$room = empty($_POST["room"]) ? false : $_POST["room"];
Can be done in PHP7 as
$room = $_POST["room"] ?? false;
A few other things are.
Keep your PHP code together if possible (makes it cleaner)
don't modify data, sanitize display. You are not displaying any user input here.
most of your inputs are not free form types. So you are doing more work then you need to (assuming function ($data) actually did anything beside cause a syntax error)
use arrays for similar types of data $errors
do not echo strings outside of HTML ( echo "Not Inserted!"; ), its ugly
end you code with HTML tag (it was missing)
don't mix quoting styles in HTML (because it irritates me)
properly indent your code, (easier to read)
don't set variable more times then you need to, it's ugly (makes it hard to read)
Database date format is Y-m-d not m/d/Y Using Date time will handle multiple formats, and put them how you need them.
be lazy, don't write code you don't need to. I was half tempted to make some loops for the <select> options, but alas It was easier to copy them. Mainly I didn't feel like explaining str_pad to add the leading 0's on the time.
use CSS not content for styling multiple times vs style="margin-right:15px" it's more precise and easier to edit.
It wasn't all bad at least you had this prepare. Also just FYI, I haven't used Mysqli in about 4 years. I mainly use PDO, so I left the DB code as is.
PS I can't really test this, so forgive me any typos
Bonus Question:How can I prevent double booking,like no records should have the same room and same time
Make room, date, start and end a compound unique key in the DB (a key that has multiple fields in it), then it will throw an error when the same data is entered. In other words when the same room is booked for the same date and times. In PDO you could use exception handling try/catch to catch those errors in Mysqli as I said I haven't used in a long time. But I imagine you'd get an error for execute. You forgot same date in same room and same time so I added that in. Because you store the date and time separately it matters.
Another way to store these would be to get rid of the date field and change Start and End to DateTime in the DB. And change this:
$start = $_POST["start"];
$end = $_POST["end"];
To
$start = $date.' '.$_POST["start"]; //2018-10-14 09:00:00
$end = $date.' '.$_POST["end"];
This way you can store the date as part of the time. Also in the future if a class spanned more then one day, you would be all set. Because you could have it start today and end tomorrow. It would also be a bit easier to work with in SQL, because of the DATE(field) and other date related functions.

Using <select> tag to update database in PHP with a submit button

I tried to find ways how to update my database for hours now and it's hurting my brain.
Please, can anyone show me how to update data inside a database by using <select>?
If I select 'Checked-Out' in the form and then click update the StatusID in the database will be updated to '2' but I just can't seem to work it.
<?php
include 'connection.php';
if(isset($_POST['submit'])){
$_var1 = $_POST['status'];
$query3 = mysql_query("UPDATE reservation SET ReservationStatusID = '$_var1' WHERE `ReservationID` = '$id' ");
if($query3)
{
header('location:viewReservedroomsGuest1.php');
}
else
{
echo "Error";
}
}
?>
Here's my select.
<select id="status">
<option value="1">Checked-In</option>
<option value="2">Checked-Out</option>
<option value="3">Pending</option>
<option value="4">Cancelled</option>
</select>
<input type="submit" name="submit" value="Update" />
I'm sorry, I don't make any sense. My brain is tired out already.
<form action="sampleupdate.php" method="post">
<select id="status" name="status">
<option value="1">Checked-In</option>
<option value="2">Checked-Out</option>
<option value="3">Pending</option>
<option value="4">Cancelled</option>
</select>
<input type="submit" name="submit" value="Update" />
</form>
in sampleupdate.php
$val = $_POST['status'];
// and write and execute the update Query here..
Put the select in a <form> with method="post"
Give the select a name attribute
Read the data from $_POST['the name you used']
Use the database API of your choice

Confused why form is not submitting

I don't think there's anything I left out, but the form doesn't seem to be transmitting any data upon hitting submit. My code is as follows, I realize it's kind of long, but I wanted to include the entire form. All of the attached functions just check if the input was valid:
<form name="formname" id="formname" action="database.php" method = post onsubmit="return checker()">
Username: <input type='text' id='un' onchange="checkname(id)" onkeyup="checkempty(id)" ><div id="un1"></div><br>
Reporter Title:<br>
<select id="s2" onblur="checktype(id)" >
<option value="choose">Choose one</option>
<option value="Assistant Director">Assistant Director</option>
<option value="Director">Director</option>
<option value="DB Admin">DB Admin</option>
<option value="Systems Admin">Systems Admin</option>
</select><div id="s21"></div>
<br>
Password: <input type='password' id='pw' onchange="checkpass(id)" onkeyup="checkempty(id)"><div id="pw1"></div><br>
Email: <input type='text' id='eml'onchange="checkemail(id)" onkeyup="checkempty(id)"><div id="eml1"></div><br>
Description:<br> <textarea rows="6" cols="20" id="desc" onchange="checkdesc(id)" onkeyup="checkempty(id)" ></textarea><div id="desc1"></div><br>
Type of Incident:<br>
<select id="s1" onblur="checktype(id)" >
<option value="choose">Choose one</option>
<option value="afs">afs</option>
<option value="password">password</option>
<option value="hardware">hardware</option>
<option value="other">other</option>
</select><div id="s11"></div>
<br>
<?php
include("connect.php");
$ret = mysql_query("SELECT * FROM countries");
echo "Choose your location:<br>";
echo "<select id='countries' onblur='checktype(id)'>";
echo "<option value='choose'>Choose one</option>";
while($array = mysql_fetch_array($ret)){
echo "<option value='{$array['abbrevs']}'>{$array['full']}</option>";
}
echo "</select><br>";
?>
<div id="countries1"></div><br>
<p>
Would you like an email copy?
<select id="s3">
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
<input type="submit" id = "sub" value= "Submit">
</p>
</form>
and the php I tried to receive it with
<?php
include("connect.php");
$username = $_GET['un'];
$password = $_GET['s2'];
$reporter = $_GET['pw'];
$email = $_GET['eml'];
$description = $_GET['desc'];
$type = $_GET['s1'];
$country = $_GET['countries'];
$emailopt = $_GET['s3'];
?>
the checker function:
function checker(){
if(isgood && isgood1 && isgood2 && isgood3 && isgood4 && isgood5 && isgood6)
{
return true;
}
else{
document.getElementById('subb').style.visibility="visible";
document.getElementById('subb').innerHTML = "You must fully complete the form.";
return false;
}
where the "isgoods" where just quick flags I made for validations, which was all working properly.
Your form's method is POST so you should use $_POST instead of $_GET in your PHP script.
Also you should fix up your HTML so it's valid, you need to quote the method attribute properly:
<form name="formname" id="formname" action="database.php" method="post" onsubmit="return checker()">
Well, I feel stupid. The problem was that I didn't give my HTML elements names, but rather just IDs. I was so used to using ajax and submitting by just getting the value with javascript via the ID that I forgot about names O.o
You are submitting your form with method="POST", so in your PHP you need to read the POST values:
$username = $_POST['un'];
...
Had you submitted your form with method="GET", your PHP code would work. Read about the difference here.

Categories