Every time when I'm running the following PHP code I'm getting output
Booking Confirmed! Congratulation. Your Booking Id is: 6
for successful booking.
The bookingid is a sequence and then I'm getting that booking id form the inserted values to get the current value of the sequence. So I don't know what I'm doing wrong.
<html><body>
<?php
$con = oci_connect("system", "password", "localhost/XE");
if (!$con) {
$m = oci_error();
exit('Connect Error ' . $m['message']);
}
$thid = $_GET["hid"];
$trno = $_GET["rno"];
$tgid = $_GET["gid"];
$sd = $_GET["sdate"];
$ed = $_GET["edate"];
$dchange = "ALTER SESSION SET NLS_DATE_FORMAT= 'YYYY-MM-DD'";
$stid1 = oci_parse($con,$dchange);
oci_execute($stid1);
$c1 = "SELECT * FROM B WHERE HOTELID = '$thid' AND ROOMNO = '$trno' AND ((STARTDATE < '$sd' AND ENDDATE > '$sd') or (STARTDATE < '$ed' AND ENDDATE > '$ed') or (STARTDATE >= '$sd' AND ENDDATE <= '$ed'))";
$c2 = oci_parse($con, $c1);
oci_execute($c2);
$row = oci_fetch_row($c2);
if(!$row)
{
$temp = "INSERT INTO B VALUES(bno.nextval,'$thid','$trno','$tgid','$sd','$ed')";
$stid = oci_parse($con,$temp);
oci_execute($stid);
oci_free_statement($stid);
//$c7 = "SELECT bookid FROM B WHERE HOTELID = '$thid' AND ROOMNO = '$trno' AND GUEStID = '$tgid' AND STARTDATE = '$sd' AND ENDDATE = '$ed'";
//printf("<h3>Booking Confirmed! Congatulation. </h3>") ;
**$c8 = oci_parse($con, "SELECT MAX(BOOKID) FROM B");
oci_execute($c8);
printf("<h3>Booking Confirmed! Congratulation. Your Booking Id is: %u</h3>", $c8);**
}
else
printf("<h3>Booking already exist. </br>Please try with another search.</h3>");
?>
</n> <form action="index.php"><input type="submit" value="BACK" />
</form>
</BODY>
a few suggestions for you.
you should be using bind variables and not splicing literals in your SQL statements (unless you want the performance of your DB to degrade as you fill the shared pool up).
SELECT MAX(BOOKID) FROM B is the wrong and unsafe way to get the booking id. as if 2 sessions in parallel made a booking, you could get wrong results (you can also get wrong results if the max id in the table is higher than the current sequence value). instead do select bno.currval from dual or use the returning clause as part of the insert (assuming PHP works with that)
on your insert you should specify the column names for good practice . i.e do INSERT INTO B (BOOKID, HOTELID, ROOMNO, STARTDATE, ENDDATE) VALUES(bno.nextval....
Related
I'm using the jQuery jeditable to allow editing an HTML table based on a MySQL database table. But its not the issue. It works great on all of the columns except one, a timeout column. I want to grab the date part of the logdate column and use it to build the timeout value. The new hour:min part is what the user has entered. The column being edited is called "timeout".
My first attempt looked like this;
if ($column == "timeout") {
$toSQL = "UPDATE NetLog t2
JOIN NetLog t1 ON t2.recordID = t1.recordID
SET t2.timeout = DATE_FORMAT(t2.logdate, '%Y-%m-%d')
WHERE t2.recordID = $recordID";
$stmt = $db_found->prepare($toSQL);
$stmt->execute();
}
This did not update the table and it did not throw any errors. And yes $value resolves to 12:34 or whatever was entered by the user. Making the new timeout value 2017-10-20 12:34.
Then I tried this;
If ($column == "timeout") { $TOSQL = "SELECT DATE_FORMAT(logdate,
'%Y-%m-%d') as dateonly, recordID
FROM NetLog
WHERE recordID = $recordID"; foreach($db_found->query($TOSQL) as $row) { $newdttm = "$row[dateonly] $value"; $recordID =
"$row[recordID]"; } $moretogo = 1; } if ($column == "timeout" AND
$moretogo == 1) { echo("$newdttm $recordID "); // 2017-10-20 12:34
8117 $sql = "UPDATE NetLog SET timeout = '$newdttm'
,timeonduty = (timestampdiff(SECOND, logdate, '$newdttm')) WHERE recordID = $recordID "; $stmt = $db_found-prepare($sql);
$stmt->execute(); }
The output of the echo looks like this: 2017-10-20 12:34 8117, which is exactly what I would expect. I've tried quite a few other things too but nothing I do updates the MySQL table. This throws a 500 error but I can't find anything wrong to cause it.
I am writing a Php 5 and Mysql 5 page counter script. When a student having id as 'visitorid' visits a page having id 'pageid' (both int(11)) the page counter tries to log the visit in 'visitors' database. But counter is not updating in mysql db, instead the visit_counter int(4) turns to 0.Whats wrong with my code? visitdate is datetime.
<?php
$pageid = 101;
$visitorid = 234;
$sql = "SELECT * FROM visitors
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("Error 1.<br>".mysql_error());
$data = mysql_fetch_array($temp);
// visit_counter is a field in table
if(($data['visit_counter']) != NULL){
echo "Entery exists <br>";
// Tried below version also
$visit = " SET visit_counter = visit_counter+1";
//$visit_counter = $data['visit_counter'];
//$visit = " SET visit_counter = ".$visit_counter++ ;
// Valid SQL
// UPDATE `visitors`
// SET visit_counter = visit_counter+1
// WHERE pageid = 101 and visitorid=234
// This manual sql query updates in phpmyadmin
$sql = "UPDATE visitors ".$visit."
AND visitdate = NOW()
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("ERROR 3.<br>".mysql_error());
//No error is displayed on above query.
} else {
//first entry
$visit_count = "1";
$sql = "INSERT INTO visitors
(`pageid`,`visitorid`, `visitdate`, `visit_counter`)
VALUES ('".$pageid."','".$visitorid."', NOW(), '".$visit_count."')";
$temp = mysql_query($sql);
//first entry is inserted successfully
//and visit_counter shows 1 as entry.
}
?>
Can anyone tell me whats wrong with this code?
Oh! I got answer by myself. Sometimes just little errors make us go crazy..
I made a mistake in udate query.. rather than using and I should have user a comma instead. .. working well now!
I am taking a users input and storing it in a database, however I want to be able to update the records if a user adds more information. So I want to search the database find the server with the same name and update the the last downtime and the number of downtimes.
$connect = mysqli_connect("localhost", "Username", "Password","Test_downtime");
if (!$connect)
{
die("Connection failed: " . mysqli_connect_error());
}else
{
echo "Connected successfully\n";
}
$servername = $_GET["server_name"];
$downtime = $_GET["downtime"];
$time_now = time();
$result = mysqli_query($connect, "SELECT COUNT(*) FROM `Test_downtime`.`Downtime` WHERE `Server_Name` = '$servername'");
$row = mysqli_fetch_array($result);
// If no downtime have been reported before
if ($row[0] == 0){
$sql = mysqli_query($connect, "INSERT INTO `Test_downtime`.`Downtime` (ID, Server_name, First_downtime, Last_downtime, Num_of_downtime,Total_downtime) VALUES (NULL, '$servername', '$time_now','$time_now',1,'$downtime'); ");
if ($sql==true) {
echo $servername . " has has its first downtime recorded\n";
}
}
//If users is already in the database
else{
$numdowntime = ($row["Num_of_downtime"] + 1);
$id = ($row["ID"]);
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
if ($sqlupdate == TRUE) {
echo "Oh No! " . $servername . " has had ". $numdowntime ." of downtimes" ;
}
}
?>
The program works fine if the server is not already in the database, the problems arise if the server is already in the database. I get the message saying it has been updated yet nothing happens to the database. How do i make it so it search and updates the records for the searched item.
So nothing append since you do not execute the sql statement ^^
Take a look here :
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
You need to use :
$sql = mysqli_query($connect, $sqlupdate);
Just after it in order to execute it.
Or at least change it to
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
Btw there is other problem but here is the main one [check out the other answer in order to found another one ]
you are fetching the result as indexed array
mysqli_fetch_array($result);
and here you are accessing results as associative array
$numdowntime = ($row["Num_of_downtime"] + 1);
change your query to
mysqli_fetch_assoc($result);
use
mysqli_num_rows($result);
to checking if you have any data
change
if ($row[0] == 0){}
to
if(mysqli_num_rows($result) ==0){}
A good approach for increasing a count in a column is using SQL to increase that.
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = (`Num_of_downtime` + 1), `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
This way you can skip your $numdowntime calculation, and the result is more accurate.
In your current setup, two users may fire the event at the same time, they both retrieve the same number from the database (ie. 9), both increasing it with one (ie. 10), and writing the same number in the database.
Making your count one short of the actual count.
SQL takes care of this for you by locking rows, and you are left with a more accurate result using less logic :)
You miss the mysqli_query() function, which actually queries the database.
$sqlupdate = mysqli_query("
UPDATE `Test_downtime`.`Downtime`
SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now()
WHERE `Server_Name` = '$servername'"
);
I want to query if there is a particular timestamp for a day using the distinct dates that are present in a table and so far I have come up with this code
$mysqli = new mysqli('localhost', 'root', 'rolemodel', 'dashboard');
$dates = "SELECT DISTINCT DATE_FORMAT(mytimestamp, '%Y-%m-%d') FROM ".$this->table_name." ORDER BY DATE(mytimestamp) ASC;";
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$rowsdata = $mysqli->query($dates); // get number of rows
$num_rows_date = $rowsdata->num_rows;
for ($i = 0; $i<=$num_rows_date; i++) {
$current_query = "SELECT mytimestamp FROM ".$this->table_name." WHERE mytimestamp =".$rowsdata[$i]; //not sure on what to use here
}
I am confused on how to query the exact timestamp which is supposed to be the particular day along with the 00:00:00
Example 2014-06-02 00:00:00
Hope my question makes sense.
try:
//$rowsdata = $mysqli->query($dates); // get number of rows
//$num_rows_date = $rowsdata->num_rows;
//for ($i = 0; $i<=$num_rows_date; i++) {
//This is usually the way you want to do this with plain old arrays
if($result = $mysqli->query($dates)){
while($row = $result->fetch_row()){
$current_query = "SELECT mytimestamp FROM ".$this->table_name." WHERE DATE(mytimestamp) ='".$row[0] . "'";
//do something awesome here ...
}
}
See the docs for the DATE function.
BUT ... it looks like you're just querying the same table you pulled the dates from in the first place, so you're guaranteed to find timestamps with those dates. Not sure what you're ultimately after, but you may be able to do it with a single query.
I need to generate an employee id for eg: E13001, the number should be auto incremented, and when the next year comes, it should be E14001(year is 2014).It should again start from 001 for every year. I have tried with yy format but the sequence number continues from the previous year. How i suppose to my change the sequence number generation ? help me. Thanks in Advance.
Well, the auto-increment on a column in MySQL will not work except for integers. Also it will increment with each field.
To do what you want, you need to separate the id and year in tow (for the mysql table). So you get a table with id,emp_id(should not be managed by the db, no AUTO-INCREMENT) and year. Then select max(emp_id) where year ='2014', so when adding a new employee you will increment that value. To get the employe id the way you need it you should merge the tow columns into one and dump the first tow chars from the year.
You should know that this then becomes a distributed e_id, and every time you need to work with it you will need to do extra work. But you keep the format you need.
Hope this helps you get an idea of how it can be done.
Hi you can try in the following way
<?php
$connection = mysqli_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("test",$connection)
or die("no connection to db");
$query3 = "SELECT * FROM simple";
$result3 = mysqli_query($query3);
$count = mysql_num_rows($result3);
if($count == 0)
{
$year = date('y');
$seq = 1;
$a = sprintf("%04d", $seq);
$emp_id = E.$year.$a;
$query= "INSERT INTO simple (emp_id) VALUES ('$emp_id')";
$result=mysqli_query($query)or die(mysql_error());
}
else
{
$query2 = "SELECT * FROM simple ORDER BY id DESC LIMIT 1";
$result2 = mysqli_query($query2);
$row = mysql_fetch_array($result2);
$last_id = $row['emp_id'];
$rest = substr("$last_id", -4);
$insert_id = "$rest" + 1;
echo $ars = sprintf("%04d", $insert_id);
$year = date('y');
$emp_id = E.$year.$ars;
$query= "INSERT INTO simple (emp_id) VALUES ('$emp_id')";
$result=mysqli_query($query)or die(mysql_error());
}
Hope this code helps you.