I am currently trying to make it so my PHP code can remove appointment records in mysql. I have been trying for quite some time without any luck.
Here is my code where you would select which appointment to remove. All of the appointments display correctly in a dropdown menu on this page.
<?php
session_start();
$db = mysqli_connect("localhost", "user", "pass", "database");
if (!$db) { die("Connection failed: " . mysqli_connect_error()); }
$sql2 = "SELECT a.appointmentID
FROM AppointmentDetail AS a, Customer AS c
WHERE a.customerID=c.customerID
AND a.appointmentStatus<>'completed'
AND emailAddress = '".$_SESSION['username']."';";
$result2 = mysqli_query($db, $sql2);
echo "<h2 class='ArticleHeader1'>Cancel one of your Upcoming Appointments</h2>";
echo "<form action='Example.php' method='post'>";
echo "<p> Select an AppointmentID from the list below </p>";
echo "<select type='text' name='appointmentCancel' required>";
while($row2 = mysqli_fetch_row($result2))
{foreach($row2 as $cell2)
echo "<option value='".$cell2."'>$cell2</option>";}
echo "</select>";
echo "<input type='submit' name='formDelete' value='Cancel Appointment' class='button'/>";
echo "</form>";
mysqli_close($db);
?>
Here is the Example.php form that I would submit to where I always get the "Sorry! There has been an error in canceling your appointment. Please contact your Administrator"
<?php
session_start();
$db = mysqli_connect("localhost", "user", "pass", "database");
if (!$db) { die("Connection failed: " . mysqli_connect_error()); }
if(isset($_POST['formDelete']))
{
$appointmentDelete = mysqli_real_escape_string($db, $_POST['appointmentCancel']);
$del_val = "DELETE FROM AppointmentDetail
WHERE appointmentID='".$appointmentDelete;."';";
$saved = mysqli_query($db, $del_val);
if($saved) {
echo "Your Appointment Has Been Successfully Cancelled!";
} else {
echo "Sorry! There has been an error in canceling your appointment.
Please contact your Administrator";
}
}
mysqli_close($db);
?>
I have tried using different SQL queries to remove records based on different fields other than appointmentID with no luck. But appointmentID is the simplest so since none of the fields are working, I must be doing something wrong.
I have also tried messing around with the quotes around $appointmentDelete and a few other variables with no luck.
I am pretty new to PHP and SQL so I really am just looking to get this basic functionality down.
I have cut out a lot of the additional code on my first PHP page to only include what I believe to be relevant.
There's an concatenation error in your delete query. Change it as bellow,
$del_val = "DELETE FROM AppointmentDetail WHERE appointmentID=$appointmentDelete";
Please refer PHP - concatenate or directly insert variables in string for more details about concatenation.
Related
I am going to start this off by saying -- yes I know there are other links similar to this and topics similar to this and I have read all of them and incorporated them into my code. However, I cannot figure it out and have tried everything I can.
Basically my goal is to take a users input from an html form called socialmedia.html:
<html>
<body>
<h1> Pulse submission page </h1><br>
<form action="action.php" method="post">
Title: <input type="text" name="posttitle"><br><br>
Content: <input type="text" name="content"><br><br>
<input type="submit">
</form>
</body>
</html>
and then send it to a php file called action.php:
<?php
$mysqli = new mysqli("DB HOST IP", "USER", "PASS", "DB NAME");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$posttitle = $_POST["posttitle"];
$content = $_POST["content"];
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle', '$content')";
echo 'post added to database';
}
if($sql){
echo 'success';
}
else{
echo 'failure';
}
$sql = "SELECT * FROM `posts`";
$res = $mysqli->query($sql);
if($res->num_rows > 0){
while($row = $res->fetch_assoc()){
echo "ID". $row["id"]. "<br/>";
echo "Title". $row["posttitle"]. "<br/>";
echo "Content". $row["content"]. "<br/>";
}
}
else
{
echo "No Record Found!";
}
?>
This file is SUPPOSED to insert the user's form values into the table posts:
this is the table posts
and then print the whole table to a webpage-- action.php this is what it prints (with the error checks and all):
this is the page, I blurred out the IP
NOTE: I manually inserted the first title and content to see if the code could read from the database (which it can)
honestly, I do not know where I went wrong and I have die extensive research at this point. It's probably going to end up being a syntax error and I'm gonna be kicking myself. It could have something to do with me using a Godaddy server and the phpMyAdmin and database being through there. I am using mysqli instead of PDO because PLESK and Godaddy do not support PDO yet.
<input type="submit" name="submit" /> try with this
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle', '$content')";
$save = $mysqli->query($sql);
if($save)
echo 'success';
else
echo 'failure';
}
several things to get you started
1) missing quote after PASS
mysqli("DB HOST IP", "USER", "PASS, "DB NAME");
2) you are not executing your INSERT query, missing $mysqli->query($sql);
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle',
'$content')";
echo 'post added to database';
}
You have to give name of the submit butto as
input type="submit" name="submit"
"INSERT INTO posts (posttitle, content) VALUES ('$posttitle', '$content')"
I have a WordPress site in which I want to show to the user a list of cities to choose from and show in a Google map.
I have made a HTML dropdown menu which I want to populate with cities which are retrieved from a MySQL table named Map_of_resellers.
Problem is, the dropdown box is shown in the page but it's empty (it has no entries).
The code I use shows me if the connection to the database is successful and also if the db query is succesfull so these are not the issues.
If you wonder what the [insert_php] and [/insert_php] tags are, they are shortcodes to allow PHP in a WordPress page since it's not supported natively.
They are used by a WordPress plugin named Insert PHP which i installed for this purpose.
Here is my PHP code:
[insert_php]
$servername = "sql102.*******.com";
$username = "b3_*******";
$password = "********";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_select_db('b3_**********');
$sql="SELECT City FROM Map_of_resellers";
$result=mysqli_query($sql);
if($result === FALSE)
{
die("Query failed: " . mysqli_error());
}
[/insert_php]
<form name="Cities" method="post" >
[insert_php]
echo "<select name='City'>";
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo "<option value='" . $row['City'] ."'>" .
$row['City']."</option>";
}
echo "</select>";
[/insert_php]
</form>
Any help would be greatly appreciated!
Looking at the source code for the plugin you mentioned, it uses eval to parse the PHP code. New variables created inside an evaluated script won't be in scope when the evaluation has ended. So $results won't be accessible in your second code block.
Replacing the code like below should keep $results in scope and fix the issue:
[/insert_php]
<form name="Cities" method="post" >
[insert_php]
to
echo '<form name="Cities" method="post" >';
I had a very random problem in an IIS class, it has stumped my tutor so here I am and I'll try my best to explain it well!
I'm running Xampp with Apache and MySQL, I run the query I want and get the expected output to a table, but I have a problem with the outputting of pictures. I have the right file type, extention and path selected, because I can get pictures to show up, but as long as at least one picture in the query result has the extension removed, and this picture will not load.
Database
Website
If I have each query result with the correct name and extension, which is the same as when it shows up, none of them show up at all!
PHP:
<?php
// set server access variables
include 'db2.inc';
// open connection
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
// select database
mysql_select_db($databaseName) or die ("Unable to select database!");
// create query
//$query = "SELECT * FROM products";
$query = "SELECT * FROM products WHERE CategoryName = 'Surfboards'";
//Check initial letter
//if (!$initialLetter=="")
//{
// $query = $query." Where country like '$initialLetter%' ";
//}
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// see if any rows were returned
if (mysql_num_rows($result) > 0) {
// yes
// print them one after another
echo "<table cellpadding=20 border=1>";
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row['ProductID']."</td>";
echo "<td>".$row['Name']."</td>";
echo "<td>".$row['Description']."</td>";
echo "<td>".$row['Brand']."</td>";
echo "<td>".$row['Model']."</td>";
echo "<td>".$row['BoardLength']."</td>";
echo "<td>".$row['BoardType']."</td>";
echo "<td>".$row['Colour']."</td>";
echo "<td>"."<img src=images/".$row['Image']."> </td>";
echo "<td>".$row['UnitPrice']."</td>";
echo "<td>".$row['CategoryName']."</td>";
echo "</tr>";
}
echo "</table>";
}
else {
// no
// print status message
echo "No rows found!";
}
// free result set memory
mysql_free_result($result);
// close connection
mysql_close($connection);
?>
Any help or direction would be greatly appreciated!
Thanks
Will
On this line:
echo "<td>"."<img src=images/".$row['Image']."> </td>";
Your image src is not enclosed in quotes. If this is a direct copy/paste of your code then that is definitely a problem, but may not be the only one.
As other people have said, look at pdo, or mysqli. The mysql_ functions you are using are deprecated for multiple reasons.
I am trying to call and update a table row in a database using certain criteria. Currently I have the table load the data in textboxes and automatically assign NAMES of all the textboxes so that I can use them later to update.
Code to display
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$check=$_POST["scenario1"];
$qwert="SELECT * FROM izprashtane WHERE Сценарий='$check'";
$query=mysqli_query($conn,$qwert);
$sql = "SHOW COLUMNS FROM izprashtane";
$result = mysqli_query($conn,$sql);
echo "<table width=650 border=1>\n";
$counter=0;
while ($get_info = mysqli_fetch_row($query)){
echo "<tr>\n";
while($row = mysqli_fetch_array($result)){
echo "<td>" . $row['Field'] . "</td>";
}
echo "</tr>\n";
echo "<tr>\n";
$counter=0;
foreach ($get_info as $field){
$counter += 1;
echo "\t<td><input type='text' name='$counter' value='$field'></td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
$conn->close();
?>
<html>
<body>
<form action="datacizprashtane.php" method="POST">
<input type="submit" value="Промяна" >
</form>
</body>
</html>
This loads the table row in a table with editable textboxes and it assigns names from 0-to however I need. Then I got the code to update the table. It is just experimental so I got only 2 textboxes and I'll add the rest once I get it going.
Code to update
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE izprashtane SET НаселеноМясто='$_POST[2]',Тримесичие='$_POST[3]' WHERE Сценарий='$_POST[6]'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
$conn->close();
At this point it gives me:
Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '�аселеноМясто='',Тримес' at line 1.
I have tried to use '".$_POST[3]."' but then it doesn't even give me the error. Any ideas of what I am doing wrong?
I think your problem is that the <input...> fields in your HTML are not inside a <form....> tag.
If fields are not placed inside a <form> they are not sent when the submit button is pressed. In fact they are not even inside the page <body>
Currently only the submit button is inside your <form> tag, which is why the submit is being actioned but no data is being passed and you are not checking the fields actually exist before using them.
Give the following a go with prepared statements:
$sql = "UPDATE izprashtane SET НаселеноМясто=?,Тримесичие=? WHERE Сценарий=?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_bind_param($stmt, "sss", $_POST['2'], $_POST['3'], $_POST['6']);
mysqli_execute($stmt);
Also, your code is a bit of a mess, make sure to escape strings using prepared statements or mysqli_escape_string to avoid SQL Injections.
EDIT:
Also, add
mysqli_set_charset($conn,"utf8");
After the second database connection while also making sure that your inputs are all in your form.
you must place all the form fields in between form tags(<form>...</form>)
ex:
<form action="datacizprashtane.php" method="POST">
<?php
//write your php code here.
?>
<input type="submit" value="Промяна" >
</form>
i hope it will help you...
i have a cart displayed and the user has to select the date of delivery from the calendar widget and click on Confirm button. on submit, the order cart should be populated along with the entered date of delivery.
the code i used is:
<?php
echo "<form action='' name='form1' >";
//some disaply codes here
echo "Choose the Date of delivery<input type='date' name='date'>";
echo "<input type='submit' class='btn btn-default' name='final_submission' value ='Confirm Order'>";
echo "</form>";
?>
the code for insertion is:
<?php
if (isset($_POST['final_submission'])){
error_reporting(E_ALL);
ini_set('display_errors', 1);
$IP="my localhost";
$USER="my user name";
$conn=mysqli_connect($IP,$USER,"","my database name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = stripslashes($_POST['date']);
$result=mysqli_query($conn, $query);
$query="select * from cart";
while($row = mysqli_fetch_array($result)) {
$us_id=$row['user_id'];
$pr_id=$row['prod_id'];
$qtty=$row['quantity'];
$query_insert = "insert into orders(user_id, prod_id, quantity, dt_del) values('.$us_id.',
'.$pr_id.', '.$qtty.','.$date.')";
$res_ins=mysqli_query($conn,$query_insert);
}
}
?>
the orders table s not getting populated. I cant put my finger on the error. plz point it out
EDIT: the orders table is getting poplulated, but the del date field is coming blank...Please let me know how to pass the date variable correctly, as clearly that is the issue
I am not sure what you are trying to attempt to be honest. Your code blocks lacks a lot of stuff. For instance:
$query="select * from cart";
while($row = mysqli_fetch_array($result)) {
What results? Where do you define them? Are that results from the query you specified there, cause surely you aint executing it. Thus the result will be 0 and will not be executed.
Also the problem is with this query it will go through every row of the cart, this means also you ll grab carts that aint belonging to your costumer, specify.
So your code should be something like
$query="select * from cart";
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_array($result)){
// yadi yadi yadi .. code code code
edit
Let me try to rework this out for you with propper indenting.
if (isset($_POST['final_submission'])){ // check if the button is correct
// error_reporting(E_ALL); <-- canceling this out for now
// ini_set('display_errors', 1); <-- canceling this out for now
$IP="my localhost";
$USER="my user name";
$conn=mysqli_connect($IP,$USER,"","my database name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = stripslashes($_POST['date']);
if (empty($date) || $date == ''){
echo 'the date is not set, please check if parameter is filled in';
} else { // if it wont pass this point, you wont get an enormous output of unidentified indexes
$query="select * from cart";
$result=mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)) {
$us_id=$row['user_id'];
$pr_id=$row['prod_id'];
$qtty=$row['quantity'];
$date = stripslashes($_POST['date']); // just to play it safe define it again
if (empty($date) || $date == ''){
echo 'something went wrong with the date';
}else{
$query_insert = "insert into orders(user_id, prod_id, quantity, dt_del) values('.$us_id.','.$pr_id.', '.$qtty.','.$date.')";
$res_ins=mysqli_query($conn,$query_insert);
}
}
}
}