I am trying to make my own booking diary with php, sql and html.
I would like to be able to prevent found booking on my booking form by checking my database to see if a record already exists before allowing my insert statement to execute.
I would ideally like to be able to do a select statement to check if a booking already exists.
IF the TIME AND DATE DOES NOT exist I would like the RADIO BUTTON PRESENT
ELSE
IF the TIME AND DATE DOES I would like the radio button NOT PRESENT .
I have been thinking long and hard but cannot think of a way to do it.
Please could I have some suggestions on how I can overcome my problem?
Thanks
My SQL Table is as follows
TABLE Bookings(
bDate Date,
bTime Time,
bName CHAR(30),
bNumber CHAR(30),
bReg CHAR(30),
bMakeModel CHAR(30)
)
This is what I have so far, but I can't think how to do it, I think I may be going about this the wrong way and perhaps a incremented for loop would be better suited:
<?php
$result = mysqli_query($con,"SELECT * FROM Bookings WHERE bDate = '$_POST[bDate]' ORDER
BY bTime;");
while($row = mysqli_fetch_array($result)){
if $_POST["bDate"] = $row['bDate'] AND $_POST["bTime"] = !$row['bTime']{
<input type="radio" name="bTime" value="08:00:00"> 8:00
}
?>
<input type="radio" name="bTime" value="08:00:00"> 8:00
<input type="radio" name="bTime" value="09:00:00"> 9:00
<input type="radio" name="bTime" value="10:00:00"> 10:00
<input type="radio" name="bTime" value="11:00:00"> 11:00<br>
<input type="radio" name="bTime" value="13:00:00"> 13:00
<input type="radio" name="bTime" value="14:00:00"> 14:00
<input type="radio" name="bTime" value="15:00:00"> 15:00
<input type="radio" name="bTime" value="16:00:00"> 16:00<br>
Until you post some code for a better help, database structure and eventually an exemple of one one or 2 rows. Here are the steps.
For checking part (form) :
If you haven't submitted your form, use AJAX to check in your database.
If you've submitted form, just execute a query on your database.
For SQL part :
A simple count can do the trick (return 0 if no rows found and n if n rows found), but retrieving an ID is better (NULL if no rows found). If you need help on query, describe the table structure, and the fields you are checking.
For the last part (showing or not the label :
In PHP, just need to test your SQL return and implement a condition test on the count value (> 0 or not), or ID (NOT NULL if row found, else NULL).
You can add the radio button (or not) depending of your test result
Tip :
Using ID is better because you can add it in an hidden INPUT tag if you've found a row. If later you decide to update it, it will be possible with this id.
Edit (with your code now) :
In your PHP code you have many errors :
-> your if condition isn't surrounded by the parentheses
-> Logical operators in PHP statement aren't like in SQL : AND (SQL) = && (PHP)
-> Inside your if, the input tag isn't in an echo. input tag is HTML not PHP
Tips :
- Are you sure you have a good connexion ($con) ressource to database?
- In sql string no need to add the final semi-colon ";"
- Always about SQL using the star alias in query run slower than enumerating each field. If one day you need to get a huge resultset, it would be an optimization
Seems nobody answered to your question. Here is a little starting code for you. Don't forget to replace with your database server, user, password and database to connect to mysql :
<?php
$mysqli = new mysqli("host", "user", "password", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>sans titre</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.23.1" />
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>Date : <input type="text" id="bDate" name="bDate" value="" /></p>
<p>Time : <input type="text" id="bTime" name="bTime" value="" /></p>
<input type="submit" value="Send" />
</form>
<hr />
<?php
/* Check if form is submitted */
if (isset($_POST["bDate"])) {
// Need a bDate format = 'YYYY-MM-DD'
if (!preg_match("/^\d{4}\-[0-1][0-9]\-[0-3][0-9]$/", $_POST["bDate"])) {
printf("dDate pattern error for SQL. Waiting YYYY-MM-DD");
exit();
}
/* Execute query */
$query = "SELECT `bDate` , `bTime` , `bName` , `bNumber` , `bReg` , `bMakeModel` FROM `Bookings` WHERE `bDate` = '". $_POST["bDate"] . "' ORDER BY 2";
$result = $mysqli->query($query);
/* Parsing result set */
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
printf ("%s (%s)<br />", $row["bDate"], $row["bTime"]);
if ($_POST["bDate"] == $row["bDate"] && $_POST["bTime"] != $row["bTime"]) {
printf ("<input type=\"radio\" id=\"bTime\" value=\"%s\" /> %s<br />", $row["bTime"], $row["bTime"]);
}
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
</body>
</html>
You have some checking on mysql connection, POST dDate variable. Also use the free once result set is no more necessary. Hope this help you.
Related
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 months ago.
I am very new to the subject of PHP and SQL working together and I have been fine so far except for updating a database row on my SQL database. I'm using parts of my lecturers code and doing exercises and my own tasks to modify the webpages and behaviour.
The process of this code is to update an article that I have set up, so I can edit the title or the code then click confirm but when I do this I get my failed return message telling me there is a parameter problem. I have often had trouble passing parameters in other languages and I have been looking and testing this for a few hours that I am hoping to receive some information and guidance on the subject.
All I want to do is update the articletext and articletitle fields.
My EDIT ARTICLE code section:
<?php
$db=createConnection();
// get the first two articles
$sql = "select blogID,articletitle,articletext,blogtime,blogposter,username,userid from blogarticle join registerdemo on blogposter = userid where blogID=?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i",$article);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($articleid,$articletitle,$articletext,$blogtime,$blogposter,$username,$userid);
//build article html
while($stmt->fetch()) {
echo "<article id='a$articleid'>
<h1>$articletitle</h1>
<p>".nl2br($articletext)."</p>
<footer><p>Posted on <time datetime='$blogtime'>$blogtime</time> by <em>$username</em></p></footer>";
// if user is logged in and not suspended add comment button
if($currentuser['userlevel']>2 || ($currentuser['userid']==$userid && $currentuser['userlevel']>1)) {
?> <form method='post' action='applychanges.php'>
<input type="text" name="articletitle" id="articletitle" size="30" required value="<?php echo $articletitle; ?>"/><br />
<textarea name="articletext" id="articletext" cols="60" rows="5"><?php echo $articletext; ?></textarea></br>
<button type="submit">Confirm</button>
</form>
<?php
}
echo "</article>";
}
$stmt->close();
$db->close();
?>
My APPLY CHANGES code:
This is where the parameters fail
<!doctype html>
<html lang="en-gb" dir="ltr">
<head>
</head>
<body>
<?php
include('php/functions.php');
if(isset($_POST['articleid']) && isset($_POST['articletitle']) && isset($_POST['articletext'])) {
$db=createConnection();
$articleid=$_POST['articleid'];
$articletitle=$_POST['articletitle'];
$articletext=$_POST['articletext'];
$updatesql="UPDATE blogarticle SET articletitle='$articletitle', articletext='$articletext' WHERE articleid='$articleid'";
$doupdate=$db->prepare($updatesql);
$doupdate->bind_param("ssi",$articletitle,$articletext,$articleid);
$doupdate->execute();
$doupdate->close();
$db->close();
header("location: index.php");
} else {
echo "<p>Some parameters are missing, cannot update database</p>";
print_r($_POST);
}
?>
</body>
</html>
Result:
Some parameters are missing, cannot update database
Array ( [articletitle] => THIS IS A TEST [articletext] => hey )
You are not posting all the parameters with your form. For example, the textarea is missing the name attribute. This will result in not posting this form field your script. Add the following line to your "Apply changes" code. This will print out the parameters you are posting.
print_r($_POST);
Check which parameters are not posted.
You probably want to add some hidden form fields.
The Update query needs to include the data variable names . Query needs to be as follows:
$updatesql="UPDATE blogarticle SET
articletitle='$articletitle', articletext='$articletext' WHERE articleid='$articleid'";
Being new to PHP and SQL, I have build a simple HTML form with 20 inputs, allowing users to enter specific data through input type=text or file. I have built a mysql database where this user data is inserted / saved. All is working, this is a major accomplishment for me.
I'm asking for help on this next step, I think this step would be called “edit”?
This step would allow users to recall the mysql data they entered, at a later time, to edit and save. Would like to have this recalled data injected directly into the original HTML form. Now, it seems necessary to have a method, (possibly a HTML form ”id “input), that calls from the data base, the specific record (including all 20 data inputs) that is associated with this user. Am I thinking correctly?
I'm asking for help / direction with simple yet detailed approach to solve this step. Note, my few attempts at this “edit” step, using some examples, have failed. I do not have a firm grasp of this PHP, yet have strong desire to become proficient.
This is a model, stripped down version of my current working code. I eliminated the $connection = mysql_connect.
This is the PHP I built, working great!
<?php
require('db.php');
if (isset($_POST['first_name'])){
$first_name = $_POST['first_name'];
$favorite_color = $_POST['favorite_color'];
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `form_data` (first_name, favorite_color, trn_date) VALUES ('$first_name', '$favorite_color', '$trn_date')";
$result = mysql_query($query);
if($result){
echo "<div class='form'><h1>First Name & Favorite Color POST to db was successfull.</h1>
<br/><h3>Click here to return <a href='https://jakursmu.com/tapcon_builder/tb_form_data_1.1.php'>TapCon Builder</a></h3>
</div>";
}
}else{
?>
This is the HTML user form, works great with the PHP script:
<div class="form">
<h1>First Name & Favorite Color "POST" to db Test</h1>
<form target="_blank" name="registration" action=" " method="post">
<p> First Name<input name="first_name" type="text" placeholder="First Name" /> </p>
<p> Favorite Color <input name="favorite_color" type="text" placeholder="Favorite Color" /> </p>
<p> <input type="submit" name="submit" value="Submit / Update to db" /></p>
</form>
</div>
Suppose the user queries the database using their “first_name”, when this “edit” step is completed, the final result will render / inject the users “first_name” and “favorite_color” back into the original HTML form. Does this make sense?
The database I created for this help post, looks like this:
database image
When a user wishes to edit their data, they can enter their "first_name", in a form text input, (im assuming?) where their "first_name" will be found in the data base. The ouutput result of this database query will be injected into the original form, ready for any user edit.
User Edit for: Results (in origingal form):
Jack Jack Black
Jeff Jeff Green
Randall Randall Red
So on.........
I hope this explanation makes sense where any experienced help or direction is offered.
Thanks for viewing!
just for practice purposes, but can look into prepared statements at you liesure time.
first create ur php file
<form method="post" action="edit.php">
<?php
//in ur php tag. select items from the row based on an id you've passed on to the page
$sql = "select * from 'form_data' where blah = '$blah'";
$result = mysqli_query($connection, $sql);
if($result){
$count = mysqli_num_rows($result);
if($count > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['firstname'];
$lname = $row['lastname'];
//you can now echo ur input fields with the values set in
echo'
<input type="text" value="'.$name.'" >
';//that how you set the values
}
}
}
?>
</form>
Finally you can run and update statement on submit of this you dynamically generated form input.
Also please switch to mysqli or pdo, alot better that the deprecated mysql.
look into prepared statements too. Hope this nifty example guides you down the right path...
This is my form
<html>
<head><title>Hawkins Car Records</title></head>
<body><h1>Add New Car</h1></body>
<form action="carNewBack.php" method="POST">
Car Name: <input type="text" name="carName"/>
<br>
Make: <input type="text" name="make"/>
<br>
Model: <input type="text" name="model"/>
<br>
Year: <input type="text" name="year"/>
<br>
Last 5 digits of VIN: <input type="text" name="lastVIN"/>
<br>
Plate: <input type="text" name="plate"/>
<br><br>
<input type="submit" value="Submit"/>
</form>
</html>
When I hit the submit button, nothing happens. No white screen, no 404, nothing. It doesn not execute carNewBack.php. Can someone share any ideas?
Here is the action file. Im trying to build a data base of service records of my family's cars and this is the form that takes input and creates a new car record.
<?php
$carconnect = mysqli_connect("localhost", "carUser", "caps271:snows", "cars");
if (mysqli_connect_errno()) {
printf("connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$carName = mysqli_real_escape_string($_POST['carName']);
$make = mysqli_real_escape_string($_POST['make']);
$model = mysqli_real_escape_string($_POST['model']);
$year = mysqli_real_escape_string($_POST['year']);
$lastVIN = mysqli_real_escape_string($_POST['lastVIN']);
$plate = mysqli_real_escaped_string($_POST['plate']);
$sql = "INSERT INTO cars (carName, make, model, year, lastVIN, plate) VALUES ('". $carName."', '".$make."', '".$model."', '".$year."', '".$lastVIN."', '". $plate."')";
$res = mysqli_query($carconnect, $sql);
if ($res === TRUE) {
echo "Car added";
} else {
printf ("Could not insert car: %s\n", mysqli_error($carconnect));
}
mysqli_close($carconnect);
}
?>
Edit: Code fixes.
your <body> tag is closed too early (on line 3), you should close it right before </html> so on line 18
Dear brother its simple..
check out your header there must be something like:
error_reporting(0); or something like that in your php.ini file to Suppress the errors.
2.There is no valid default function as mysqli_real_escaped_string(); unless you have it user defined.
It is mysqli_real_escape_string();
kindly have a look at mysqli_real_escape_string()
hope it was helpful :)
if carNewBack.php is not printing anything back to the screen or redirecting the page. What are using to host the website? If you do not have a web service that does not have php support then this could be an issue.
The form you submitted looks correct (http://www.w3schools.com/php/php_forms.asp), I imagine the real issue could lie in the php handler. If you do not get an error, that means that it does find the php handler.
I also tested your code and it looks fine, so another option could be the browser you are using or even the zoom (I use Google Chrome).
Before anybody says, I will protect myself against SQL injections, right after I fix this error. I am making an app where news reports are submitted to the database. This page is what removes a report from the database.
What I have tried:
Every possible way of adding brackets to the SQL and speech marks. My ICT teacher and I have looked at this for nearly 2 hours and cannot find a fix. I have also searched Google and Stack Overflow but I cannot find an answer.
Ok, so the correct report_id displays when I echo it. When I put the actual id, eg 5, the report is deleted. But when I put $report_id, nothing is deleted.
Please could somebody tell me what correction I have to make to get this to work ?
Here is the code (EDIT: This is the fixed code. I added the hidden field in the form at the bottom, among a few other small changes (like taking out the extra form tag)):
<?php
require_once('authorize.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Football Central - Remove a Report</title>
</head>
<body>
<h2>Football Central - Remove a News Report</h2>
<?php
require_once('img_details_reports.php');
require_once('connect_db_reports.php');
//Assign variables from admin_reports.php using $_GET
$report_id = $_GET['id'];
if (isset($_POST['submit'])) {
if ($_POST['confirm'] == 'Yes') {
$report_id = $_POST['id'];
// Delete the image file from the server
#unlink(IMAGE_UPLOADPATH . $image);
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die("Unable to connect to the database.");
// Delete the score data from the database
$query = "DELETE FROM news_reports WHERE report_id = '".$report_id."' LIMIT 1"
or die("mysql_query failed - Error: " . mysqli_error());
mysqli_query($dbc, $query) or die("mysql_query failed - Error: " . mysqli_error());
mysqli_close($dbc);
}
}
//Display form to confirm delete
echo '<p>Are you sure you want to delete the news report?</p>';
echo '<form method="post" action="removereport.php">';
echo '<input type="radio" name="confirm" value="Yes" /> Yes ';
echo '<input type="radio" name="confirm" value="No" checked="checked" /> No <br />';
echo '<input type="hidden" name="id" value="' . $report_id . '" />';
echo '<input type="submit" value="Submit" name="submit" />';
echo '</form>';
echo '<p><< Back to admin reports page</p>';
?>
</body>
</html>
Your are mixing two statements. Just try below.
// Delete the score data from the database
$query = "DELETE FROM news_reports WHERE report_id = ".$report_id;
mysqli_query($dbc, $query) or die("mysql_query failed - Error: " . mysqli_error($dbc));
You are sending the form with post method and retrieving it with get. That can be the source of the problem.
Also you are not sending the id parameter so, there won't be any value for $_get[id] nor $_post[id]
You shouldn't have to wrap the ID in single-quotes, if the ID is a number.
$query = "DELETE FROM news_reports WHERE report_id = '".$report_id."' LIMIT 1"
But that's not the problem. You did not include the ID in your confirmation request, or allow for retrieving the value from a session variable. Add a hidden input box with the id, in your "Display form to confirm delete" section.
(And have a different code branch for confirmation! And a test for an invalid ID! And move this to POST, at the very least!)
You've got
$query = "..." or die(...);
Why?
Also, you've got two form opening tags -- it's not valid to nest forms.
I'm going to assume that the id variable comes in from some source other than the form because there's no form element that submits it.
Finally, make sure to specify get or post in your form. I'd recommend using post, and then change $_GET["submit"] and $_GET["confirm"] to $_POST["submit"] and $_POST["confirm"].
You need to check following things in your code.
Where is your ID element in the form
You have put POST method in form but retrieving data from $_GET, you should change it to $_POST.
Put mysqli_error after mysqli_query statement.
$query = "DELETE FROM news_reports WHERE report_id = ".$report_id;
mysqli_query($dbc, $query); or die("mysql_query failed - Error: " . mysqli_error());
Then check the error from mysql if it does not work.
Hope, it will help you in solving your issue.
I am trying to make a webpage that connects to my SQL database and fetches information from a table and place it into a text box. The information it fetches is dependent on what is entered into another text box. Essentially its an "autofill" of information. I was curious whether this was possible.
To create a better understanding here is a layout of text boxes:
<html>
<head>
<?php
$con = mssql_connect("abc", "123", "password");
if (!$con)
{
die('Could not connect: ' . mssql_get_last_message());
}
mssql_select_db("db1", $con);
$result = mssql_query("SELECT * FROM FormData");
<head>
<title>test</title>
</head>
<body>
<h1>test</h1>
<form action="#">
<p>Enter ID</p>
<input type="text" name="ID"/>
<input type="text" name="NAME"/>
<input type="text" name="LASTNAME"/>
<input type ="button" value="submit" onclick="check(ID)" />
</form>
</body>
Here an ID would be entered into a text box and then once the submit button was pressed, it would fetch the rest of the information from my sql database into the next boxes. I don't even know whether this is possible, whether I can use Javascript in conjunction with this or something. I searched but couldn't find much help on the subject.
I'm not even sure if its possible to do "if" statements within SQL - whenever I try I end up with a 500 error due to improper syntax.
If I understand you correctly, all you need to do is on the submission of the form capture the ID they entered.
If the ID has not been submitted yet (either their first time hitting the page, or they failed to enter an ID) you should not perform any query and create a blank $row array like so:
$row = array("ID" => "", "NAME" => "", "LASTNAME" => "");
You should then fill your form fields using this array <input type="text" name="NAME" value="<?php echo $row['NAME']; ?>"/>.
If the ID has been submited you then use this ID in your SQL query "SELECT * FROM FormData WHERE ID = $_POST['ID']" (Note: This is an example. You will need to escape the POST data to prevent SQL injection).
You need to then pull this result into your $row array $row = mysql_fetch_row($result) which in turn is used by your fields to populate the value.
This entire procedure could be done with AJAX so that you don't have to perform a full page submit however based on your example the solution I have provided should be good enough.