Receiving an error "ORA-00904: "ORDERNUMBER": invalid identifier" for php? - php

It says the error code is indentified at line 69 and line 72, which the codes are:
Line 69: OCI_Execute($stmt);
Line 72: if(OCI_Fetch($stmt)) {
Here is my following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
/* Set oracle user login and password info */
$dbuser = "..."; /* your [login */
$dbpass = "..."; /* your oracle access password */
$db = "SSID";
$connect = OCILogon($dbuser, $dbpass, $db);
if (!$connect) {
echo "An error occurred connecting to the database";
exit;
}
// Extract form data
$book1 = $_REQUEST['book1'] ;
$price1 = $_REQUEST['price1'] ;
$quantity1 = $_REQUEST['quantity1'] ;
$subtotal1 = $_REQUEST['subtotal1'] ;
$book2 = $_REQUEST['book2'] ;
$price2 = $_REQUEST['price2'] ;
$quantity2 = $_REQUEST['quantity2'] ;
$subtotal2 = $_REQUEST['subtotal2'] ;
$book3 = $_REQUEST['book3'] ;
$price3 = $_REQUEST['price3'] ;
$quantity3 = $_REQUEST['quantity3'] ;
$subtotal3 = $_REQUEST['subtotal3'] ;
$book4 = $_REQUEST['book4'] ;
$price4 = $_REQUEST['price4'] ;
$quantity4 = $_REQUEST['quantity4'] ;
$subtotal4 = $_REQUEST['subtotal4'] ;
$grandtotal = $_REQUEST['grandtotal'] ;
// get the max ID in plants table and allocate $ID+1 for the new record
$max_id_stmt = "SELECT max(ID) FROM bookorder ";
// check the sql statement for errors and if errors report them
$stmt = OCIParse($connect, $max_id_stmt);
if(!$stmt) {
echo "An error occurred in parsing the sql string.\n";
exit;
}
OCIExecute($stmt);
$ID =0;
if(OCIFetch($stmt)) {
$ID= OCIResult($stmt,1); //return the data from column 1
}else {
echo "An error occurred in retrieving book id.\n";
exit;
}
$ID++;
// get the max ID in plants table and allocate $ID+1 for the new record
$max_OrderNumber_stmt = "SELECT max(OrderNumber) FROM bookorder ";
// check the sql statement for errors and if errors report them
$stmt = OCIParse($connect, $max_OrderNumber_stmt);
if(!$stmt) {
echo "An error occurred in parsing the sql string.\n";
exit;
}
OCI_Execute($stmt);
$OrderNumber =1111;
if(OCI_Fetch($stmt)) {
$OrderNumber= OCIResult($stmt,1); //return the data from column 1
}else {
echo "An error occurred in retrieving book order number.\n";
exit;
}
$OrderNumber++;
// Create the SQL statement to add the data. Note: field value should be single quoted '' if VARCHAR2 type.
$sql = "INSERT INTO plantorder (ID, OrderNumber, plant1, price1, quantity1, subtotal1, plant2, price2, quantity2, subtotal2, plant3, price3, quantity3, subtotal3, plant4, price4, quantity4, subtotal4, grandtotal) VALUES ($ID, '$OrderNumber', '$plant1', '$price1', '$quantity1', '$subtotal1', '$plant2', '$price2', '$quantity2', '$subtotal2', '$plant3', '$price3', '$quantity3', '$subtotal3', '$plant4', '$price4', '$quantity4', '$subtotal4', '$grandtotal')";
// Add the data to the database as a new record
$stmt = OCIParse($connect, $sql);
if(!$stmt) {
echo "An error occurred in parsing the sql string.\n";
exit;
}
OCIExecute($stmt);
$order_count_sql = "SELECT max(OrderNumber) FROM plantorder";
$stmt = OCIParse($connect, $order_count_sql);
if(!$stmt) {
echo "An error occurred in parsing the sql string.\n";
exit;
}
OCIExecute($stmt);
$order_count =0;
// retrieve the max order number
if(OCIFetch($stmt)) {
$order_count = OCIResult($stmt,1); //return the data from column 1
}else {
echo "An error occurred in retrieving order id.\n";
exit;
}
echo("Your order has been received; please quote Order Number #".$order_count." in any correspondence. Thank you.");
?>
</body>
</html>
i have left out the login and password info just to let you know, that isnt causign the error :) Kind Regards

Related

inserting mysql date field into MySQL Database

I'm having an issue submitting a form into a database once I have added a Submitted_Date field.
The errors are as follows:
Fatal error: Uncaught mysqli_sql_exception: Incorrect date value:
'2022' for column 'Submitted_Date'
mysqli_sql_exception: Incorrect date value: '2022' for column
'Submitted_Date'
Prior to adding in $Submitted_Date = date('Y-m-d', strtotime($_POST['Submitted_Date'])); I was also getting an error for incorrect listed fields on the binding.
The Submitted_Date field is a date input field so needs to be handled as 'NULL' value if a date has not been entered. Instead I also get a
'Incorrect date value: '1970'
Any help would be great. Thanks.
<?php
if (isset($_POST['submit'])) {
$sql = $conn->prepare("UPDATE orders SET Publisher_Email=? , Client_Name=? , Submitted_Date=? WHERE PC_Job_Number=?
");
$Publisher_Email = $_POST['Publisher_Email'];
$Client_Name = $_POST['Client_Name'];
$Submitted_Date = date('Y-m-d', strtotime($_POST['Submitted_Date']));
$sql->bind_param("ssii", $Publisher_Email, $Client_Name, $Submitted_Date, $_GET["PC_Job_Number"]);
if (empty($Submitted_Date)) {
$Submitted_Date = "NULL";
}
if($sql->execute()) {
$success_message = "Edited Successfully";
} else {
$error_message = "Problem in Editing Record";
}
}
$sql = $conn->prepare("SELECT * FROM orders WHERE PC_Job_Number=?");
$sql->bind_param("i",$_GET["PC_Job_Number"]);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
}
$conn->close();
?>

Resource id #6 error, Not sure how to fix it

I keep getting a 'Resource id # 6' failure when submitting a script on my website. The code I'm using is the same type of code I use for registering for the website and that works but this script doesn't work at all. What my code does is send a booking request with the fields as shown to the database. I keep getting a Resource id#6 error , and I've googled what that is but I can't seem to figure out whats wrong. I am a beginner at php , so any tips on whats to look for to avoid a resource id # 6 error would be a lot of help
<?php
//$pattern="/^.+#.+/.com/";
//error_reporting(0);
if(isset($_POST["submit"])){
$Name_of_Person = $_POST['Name_of_Person'];
$Name_of_Group = $_POST['Name_of_Group'];
$room = $_POST['room'];
$How_Many_People = $_POST['How_Many_People'];
$Date_of_Booking = $_POST['Date_of_Booking'];
$End_time = $_POST['End_time'];
$Purpose = $_POST['Purpose'];
$Contact_Number = $_POST['Contact_Number'];
$Contact_Email = $_POST['Contact_Email'];
$Alcohol = $_POST['Alcohol'];
$Security = $_POST['Security'];
$Projector = $_POST['Projector'];
$Extra_Chairs = $_POST['Extra_Chairs'];
$Extra_Info = $_POST['Extra_Info'];
$Activated = '0';
$con = mysql_connect('localhost','root','test123') or die("couldn't connect");
mysql_select_db('bookerdb') or die("couldn't connect to DB");
//if(filter_var($email, FILTER_VALIDATE_EMAIL)){//(preg_match($pattern, $_POST['Contact_Email'])){
$query = mysql_query("SELECT * FROM `booking_table` WHERE Date_of_Booking='".$Date_of_Booking."' AND room='".$room."'");
$numrows = mysql_num_rows($query);
echo $query;
if($numrows==0){
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
$result = mysql_query($sql);
if($result){
echo "Sent to be approved";
$redirect_page = '../ASC.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}else{
echo "Failed";
}
}else{
echo"There is already a requested booking on that date & time";
$redirect_page = '../EAR.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}
/*}else{
echo "error";
$redirect_page = '../EWF.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}*/
}
?>
You have error in your second SQL query. You try to insert 14 values into 15 columns (in values you forgot $Contact_Email).
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Contact_Email','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
Than remove echo $query from your code, line 30.
In $query isn't query, but mysql result object. You can't work with that by this way, you can't echo it.

PHP and SQL: using login session variable not updating the database correctly

I am creating a page where a user can calculate their BMI and then save this to their profile. First I validate the BMI. However, when I perform this calculation now, it is inserting '0.99' into the database instead of the correct BMI value. I have been debugging and think it has something to do with the connection to the database (have tried moving this around to other areas of the script but it isn't making a difference).
The code is below:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<link rel="stylesheet" href="css.css" type="text/css" />
<body>
<?php
error_reporting(E_ALL &~ E_NOTICE);
// Start the session
session_start();
// Make sure the browser is transmitting in UTF-8
header('Content-type: text/html; charset=utf-8');
// Clear the error message
$error_msg = "";
if (isset($_SESSION['user_id']))
echo $_SESSION['user_id'];
$dbc = mysqli_connect('localhost', 'root', 'root', 'help_me_be_healthy') or die("Error " . mysqli_error($dbc));
mysqli_set_charset($dbc, "utf8");
if(isset($_POST['submit']))
{
$bmi=0;
$kg=$_POST['kg'];
$mt=$_POST['mt'];
if(empty($kg) || empty($mt))
{
echo "<label class='err'><center>All fields are required</center></label>";
include("index.php");
}
else if(!is_numeric($kg) && !is_numeric($mt) )
{
echo "<label class='err'>Please enter valid data.</label>";
include("index.php");
}
else
{
$bmi = $kg/($mt*$mt);
$bmi=round($bmi,2);
if ( $bmi <= 18.5 )
{
echo "Your BMI is " .$bmi." which means you are underweight";
}
else if ( $bmi>18.5 && $bmi <= 24.9) {
echo "Your BMI is ".$bmi." which means you are normal";
}
else if ( $bmi>29.9 && $bmi> 24.9 ) {
echo "Your BMI is ".$bmi." which means you are overweight";
}
else if ( $bmi >29.9 && $bmi<=39.9 ) {
echo "Your BMI is ".$bmi." which means you are obese";
}
else
{
echo "You are morbidly obese.";
}
include("index.php");
//$query = "UPDATE `users` SET `user_bmi`= '$bmi'
//WHERE `user_id` = ($_SESSION = ['user_id'])";
//echo $_SESSION['user_id'];
//if (!isset($_GET['user_id'])) {
//$query = "SELECT * FROM 'users'";
$query = "UPDATE `users` SET `user_bmi`= '$bmi' WHERE `user_id` = '" . $_SESSION['user_id'] . "'";
//}
//else {
// $query = "UPDATE `users` SET `user_bmi`= '$bmi' WHERE `user_id` = '" . $_GET['user_id'] . "'";
//}
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_assoc($data);
print "\n----\nLookup:\n";
print "Num rows: " . mysqli_num_rows($data);
print "\n";
print_r($row);
print '</pre>';
return;
}
}
?>
</body>
</html>
Any help would be much appreciated:)
Sarah
Assuming BMI is being calculated correctly/displayed, and the user_bmi column is a float/double/numeric/decimal, the UPDATE doesn't need quotes around the value so the SQL should be:
$query = "UPDATE `users` SET `user_bmi`=$bmi WHERE `user_id`=".
$_SESSION['user_id'];
(user_id my also not need to be escaped, depending if it's a number or a string)
Also, you cannot get a query result (fetch_assoc) from an UPDATE SQL command... if you'd like to know the number of effected rows use mysqli_affected_rows:
print "Num rows: ".mysqli_affected_rows($dbc);
What makes you think the BMI is going in incorrectly, are you sure the user_id is correct, how are you looking into the database to determine what's stored?
Updated Code Printout code:
if (!mysqli_query($dbc,$query)) {
echo "Failed to store";
}
echo "<pre>\n----\nLookup:\nQuery:$query\n".
"Num rows:".mysqli_affected_rows($dbc)."\n</pre>\n";

PHP certain part of code is not executing

Hi I am facing a unique issue with my PHP script.Here is my code. After writeToDB() is executed I dont see the echo ("<script> top.location.href=www.facebook.com</script>");
Can someone let me know why my script stops executing after writing to db?
<?php
function writeToDB($access_token,$uid,$username,$birthday,$gender,$age)
{
/* Database Connection */
$user = "xxxx";
$password = "xxxx";
$host = "xxxxxxxxxxxxxxxxxx";
//connect to database, where tsnames.ora is setup
$connect_obj = oci_connect($user, $password, $host);
if ($connect_obj) {
error_log("connected okay");
} else {
$err = OCIError();
echo "Oracle connection error " . $err[text];
return;
}
$select_query = "SELECT USER_ID FROM FBTABLE WHERE USER_ID= '$uid'";
$select_sql_stmt = oci_parse($connect_obj, $select_query);
//execute statement
try {
$r = oci_execute($select_sql_stmt, OCI_DEFAULT);
if (!$r) {
$p = oci_error($select_sql_stmt);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
$user_id_in_db = null;
while (oci_fetch($select_sql_stmt)) {
$user_id_in_db = oci_result($select_sql_stmt, 'USER_ID');
}
// User already exists in db so update instead of insert
if ($user_id_in_db != null) {
$query ="UPDATE FBTABLE SET ACCESS_TOKEN='$access_token' WHERE USER_ID='$uid'";
} else {
$query = "INSERT INTO FBTABLE(ACCESS_TOKEN, USER_ID,USER_NAME,BIRTHDAY,GENDER,AGE)
VALUES
('$access_token','$uid','$username','$birthday','$gender','$age')";
}
//create sql statement
$sql_statement = oci_parse($connect_obj, $query);
//execute statement
try {
$r = oci_execute($sql_statement, OCI_DEFAULT);
if (!$r) {
$p = oci_error($sql_statement);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
//Commit transaction
$committed = oci_commit($connect_obj);
//Test whether commit was successful. If error occurred, return error message
if (!$committed) {
$error = oci_error($conn);
echo 'Commit failed. Oracle reports: ' . $error['message'];
}
//close the connection
$oci_free_statement($sql_statement);
if (oci_close($connect_obj)) {
echo " oci connection not closed!!!";
}
//close the connection
$oci_free_statement($sql_statement);
}
?>
<html>
<body>
<?php
$access_token = $_GET['access_token'];
$uid = $_GET['uid'];
$username = $_GET['username'];
$birthday = $_GET['birthday'];
$gender = $_GET['gender'];
$age = $_GET['age'];
echo $username;
writeToDB($access_token,$uid,$username,$birthday,$gender,$age);
echo ("<script> top.location.href=www.facebook.com</script>");
?>
</body>
</html>
i think error is in $oci_free_statement($sql_statement); must be oci_free_statement($sql_statement); extra $ before oci_free_statement
http://php.net/manual/en/function.oci-free-statement.php
no any error show because of error_display is off
Your JavaScript code should be
echo ("<script> top.location.href='http://www.facebook.com';</script>");
It's happen because writeToDB() causes error. You don't see this error because error_display is off or error_reporting = 0
Also maybe you didn't install OCI8. So when you call oci_connect it will cause error.
Thanks.
you are not using quotes around the string:
www.facebook.com should be 'www.facebook.com'

why am i receving an undefined index error for this $_SESSION variable

I don't know why I am receving this error but it keeps stating that I have an undefined index: AudioFile on line 35 in code below:
<?php
ini_set('display_errors',1);
session_start();
?>
<body>
<?php
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
unlink("AudioFiles/" . $_SESSION['AudioFile']);
$delete = $mysqli->prepare('DELETE FROM Audio WHERE AudioId = ?');
$delete->bind_param("i",$_SESSION['lastAudioID']);
$delete->execute();
$deleteaud = $mysqli->prepare('DELETE FROM Audio_Question WHERE AudioId = ?');
$deleteaud->bind_param("i",$_SESSION['lastAudioID']);
$deleteaud->execute();
?>
</body>
</html>
I don't quite understnd why I am recieving this index error. Does anyone know why I am receving this error?
I defined the $_SESSION variable in the audioupload.php page which is below
<?php
ini_set('session.gc_maxlifetime',12*60*60);
ini_set('session.gc_divisor', '1');
ini_set('session.gc_probability', '1');
ini_set('session.cookie_lifetime', '0');
require_once 'init.php';
session_start();
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$result = 0;
if ((($_FILES["fileAudio"]["type"] == "audio/wav")
|| ($_FILES["fileAudio"]["type"] == "audio/wma")
|| ($_FILES["fileAudio"]["type"] == "audio/mp3")
|| ($_FILES["fileAudio"]["type"] == "audio/m3u")
|| ($_FILES["fileAudio"]["type"] == "audio/iff")
|| ($_FILES["fileAudio"]["type"] == "audio/mid")
|| ($_FILES["fileAudio"]["type"] == "audio/m4a")
|| ($_FILES["fileAudio"]["type"] == "audio/mpa")
|| ($_FILES["fileAudio"]["type"] == "audio/aif")
|| ($_FILES["fileAudio"]["type"] == "audio/wa"))
&& ($_FILES['fileAudio']['size'] > 0))
{
if( file_exists("AudioFiles/".$_FILES['fileAudio']['name'])) {
$parts = explode(".",$_FILES['fileAudio']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("AudioFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileAudio']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileAudio"]["tmp_name"],
"AudioFiles/" . $_FILES["fileAudio"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileAudio"]["tmp_name"],
"AudioFiles/" . $_FILES["fileAudio"]["name"]);
$result = 1;
}
$audiosql = "INSERT INTO Audio (AudioFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($audiosql)) {
// Handle errors with prepare operation here
}
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$aud);
//Assign the variable
$aud = 'AudioFiles/'.$_FILES['fileAudio']['name'];
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$lastAudioID = $mysqli->insert_id;
$_SESSION['lastAudioID'] = $lastAudioID;
$_SESSION['AudioFile'] = $_FILES["fileAudio"]["name"];
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$sessionquery = "SELECT SessionId FROM Session WHERE (SessionName = ?)";
if (!$sessionstmt = $mysqli->prepare($sessionquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
// Bind parameter for statement
$sessionstmt->bind_param("s", $sessid);
// Execute the statement
$sessionstmt->execute();
if ($sessionstmt->errno)
{
// Handle query error here
echo __LINE__.': '.$sessionstmt->error;
break 1;
}
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$sessionstmt->bind_result($sessionid);
// This populates $optionid
$sessionstmt->fetch();
$sessionstmt->close();
$audioquestionsql = "INSERT INTO Audio_Question (AudioId, SessionId, QuestionId)
VALUES (?, ?, ?)";
if (!$insertaudioquestion = $mysqli->prepare($audioquestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err audioquestion";
}
$qnum = (int)$_POST['numaudio'];
$insertaudioquestion->bind_param("iii",$lastAudioID, $sessionid, $qnum);
$insertaudioquestion->execute();
if ($insertaudioquestion->errno) {
// Handle query error here
}
$insertaudioquestion->close();
}
?>
<script language="javascript" type="text/javascript">window.top.stopAudioUpload(<?php echo $result; ?>, '<?php echo $_FILES['fileAudio']['name'] ?>');</script>
</body>
</html>
Undefined index means the key 'lastAudioID' does not exist in $_SESSION. You can check this with:
if(array_key_exists('lastAudioID', $_SESSION)) {
// Key exists
}
Seems you did not set the key (or not correctly) in your Code.
Edit:
It may be because you include your file after you have outputted already something. try to include the file before you output anything. I am pretty sure this is it.

Categories