Date insertion to php table via php failing - php

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);
}
}
}
}

Related

Cannot get my PHP code to remove row in mysql

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.

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

How can I SELECT field FROM table WHERE id=variable?

I have a variable of the logged in user ($steamid) that I need to use to select and echo specific fields from the database. I am using the following code, but it is working incorrectly. All database info is correct, the tables, columns, and variables are not misspelled. Not sure what I'm doing wrong.
<?php
$con=mysqli_connect("private","private","private","private");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `bananas` FROM `es_player` WHERE `steamid` = '$steamID'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("bananas: %n",$fieldinfo->bananas);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
No errors are shown, it simply returns "bananas:" with nothing after it. I feel like I didn't to it correctly, does anyone know what I might've done wrong? Here is a screenshot of my database table so you know what it looks like http://puu.sh/gCY3d/983b738458.png.
Try this:
$query = Mysqli_Query($con, "SELECT * FROM `es_player` WHERE `steamid`='$steamID'") or die(mysql_error());
if( ! mysqli_num_rows($query) )
{
echo 'No results found.';
}
else
{
$bananas_array = mysqli_fetch_assoc($query);
$bananas = $bananas_array['bananas'];
echo 'Number of bananas: '. $bananas;
}
If this doesn't work, there is a problem with STEAM_ID format. You could try triming the IDs to be JUST a number, and add the STEAM_x:x: to it later.

insert value from drop down box to the database

I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";

Echo statement in PHP not executing in a specific manner

I'm having a problem with some specific PHP code that I've been working on for a few days. It's meant to be a reporting code where I can input a day and a month and it will list the total sales of that particular day.
But, I can't seem to make the last statement whereby, if there are no values(there are no data) in the query, it will display 'No Sales on this particular day'. Here's the code I've been working on. But the last echo statement is not executing. Any ideas?
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
$day=#$_POST['day'];
$month=#$_POST['month'];
echo "<center><h2>Sales report on " .$day. "." .$month. ".2013</h2></center>";
echo "<center><table style='border:2px solid black;' align=center width=600>";
echo "<tr><th colspan=12><center><h2>Sales Report</h2><hr size='2' color='black' /></center></th></tr>";
echo " <th width=400> Amount Collected</th>";
?>
<br>
<?php
$x = 1; //counter
//open a connection to a MySQL server using function mysql_connect
//returns a MySQL link identifier on success, or FALSE on failure.
$conn= mysql_connect("localhost","root","");
if (!$conn)
die ("Connection error: ".mysql_error());
else {
//select a MySQL database
//returns TRUE on success or FALSE on failurue.
$db=mysql_select_db("cqfos");
if(!$db)
die ("DB not found: ".mysql_error());
else {
//put query in a variable $query
$query= "select ROUND(sum(orderdetails.tprice),2)
from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '$day' AND MONTH(orders.date) = '$month'";
$result=mysql_query($query);
if(!$result)
die ("Invalid query: ".mysql_error());
//if record exists
else {
//fetch a result row as both associative array and numeric array
if(mysql_num_rows($result)== 1){
while ($row=mysql_fetch_array($result,MYSQL_BOTH)){
echo "<tr>";
echo "<td align='center'>RM ".$row[0]."</td></tr>";
$x++; //increase the counter
}
}
else {
echo "<tr><th colspan=12>No sales made.</td></tr>";}
}
}
}
echo"</table></center>";
?>
Several problems here
your HTML table syntax is incorrect, and your using an old sql library - and it dose not look like your SQL syntax is right... try this code (not tested as I don't have your data)
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
echo '<div style="margin:auto; textalign:center;">';
echo "<h2>Sales report on " .$_POST['day']. "." .$_POST['month']. ".2013</h2>";
echo "<h2>Sales Report</h2>"
echo "<table style='border:2px solid black;' align=center width=600>";
echo "<tr><th width=400> Amount Collected</th></tr>";
?>
<br>
<?php
$conn = new mysqli("localhost","root","","cqfos");///use mysqli, not mysql : mysql is depricated
if ($conn->mysqli)
exit ("Connection error: ".$conn->errno ." : " $conn->error);
else {
//put query in a variable $query
$eDay = $conn->mysql_real_escape_string($_POST['day']);//escape these to protect the database
$eMonth = $conn->mysql_real_escape_string($_POST['month']);;//escape these to protect the database
//your column name is probably not a rounded value, replaced it with * (return all columns)
$query= "select * from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '"
.$eDay."' AND MONTH(orders.date) = '".$eMonth."'";
$result=$con->query($query);
if($conn->errno)
exit ("Invalid query: ".$conn->errno ." : " $conn->error);
//if record exists
else {
$numericArray = $result->fetch_array(MYSQLI_NUM); //fetch a result row as numeric array
$associativeArray = $result->fetch_array(MYSQLI_ASSOC); //fetch as an associtive array this is not used, just an example
$bothArray = $result->fetch_array(MYSQL_BOTH); //both associtive and numeric this is not used, just an example
}
if(!empty($numericArray))
{
foreach ($numericArray as $value) {
echo "<tr><td>RM ".$value[0]."</td><tr>";//is there more then 1 col? if not you should consider an html list
}
} else {
echo "<tr><td>No sales made</td><tr>";
}
echo"</table></center>";
}
?>
Your SQL (likely) returns more than only one row, so change the line I mentioned before to this:
if(mysql_num_rows($result)>0){
Just letting you know your code is vulnerable to SQLi because you have not sanitized $day and $month. Also please consider using PDO.
If you haven't already - Try running the SQL statement into PHPMyAdmin and see where it outputs the error (if there is one), else it will output the data.*
*Manually inputting the day/month substituting for the variables.

Categories