I have a script with the following code to insert data into an Oracle table:
$sql = "INSERT INTO EXAMPLE_TABLE (ID, FIELD, VAL) VALUES (:id, :test, :ok)";
$stid = oci_parse($conn, $sql);
//die("parsed ok");
oci_bind_by_name($stid, ":id", $id);
oci_bind_by_name($stid, ":test", $test);
oci_bind_by_name($stid, ":ok", $ok);
//die("params bound");
$result =#oci_execute($stid);
if(!$result)
{
$err = oci_error($stid);
$error = $err['message'];
echo $error; die('end error');
}
echo oci_num_rows($stid) . " rows inserted.<br />";
die("inserted");
The script was working fine, and then it just stopped. I threw in some die statements to find where the script is stalling. The last place I can get to is "die("params bound")".
I've verified that the variables are ok and that the database connection is valid. I also manually connected to the database using sqldeveloper and had no problem.
Why is this script suddenly stalling?
As often happens, I had a though immediately after I posted this question. I checked to see how many connections I had open in a GUI, and then closed the connections.
It turns out that I had some uncommitted changes from some queries that I ran manually in my GUI, and I think that was stalling the script at oci_execute. After rolling back the changes and restarting my connection, the script works fine now.
Related
I have a web page created in php using html code. I want to save user information entered in my web page to a MySQL database. I am using php as the middle man to link the frontend web page(htmnl code) to the database(mysql).
Inside my link folder (middle man php file) I have the following:
<?php
//Gets server connection credentials stored in serConCred2.php
require_once('ConCred2.php');
//SQL code for connection w/ error control
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(!$con){
die('Could not connect: ' . mysqli_connect_error());
}
//Selection of the databse w/ error control
$db_selected = mysqli_select_db($con, DB_NAME);
if(!$db_selected){
die('Can not use ' . DB_NAME . ': ' . mysqli_error($con));
}
//Co-PI and Co-Investigator Information variables
$Co_FNAME = $_POST['fname'];
$Co_LNAME = $_POST['lname'];
$Co_SLNAME = $_POST['slname'];
$Co_DEGREE = $_POST['Degree_Selection'];
$Co_DEGREE_Other = $_POST['other_specify_degree']; //hold the value of degree if user selected other from the dropdown menu
$Co_CPOS = $_POST['Current_Position_Selection'];
$Co_CPOS_Other = $_POST['other_specify_cpos']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_INST = $_POST['Institution_Selection'];
$Co_INST_Other = $_POST['other_specify_inst']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_SCHOOL = $_POST['School_Selection'];
$Co_SCHOOL_Other = $_POST['other_specify_school']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_DEPART = $_POST['Department_Selection']; //Este se estara eliminando en la version online
$Co_DEPART_Other = $_POST['other_specify_department']; //hold the value of Department if user selected other from the dropdown menu
$Co_PROGRAM = $_POST['program'];
$Co_EMAIL = $_POST['email'];
$Co_PHONE = $_POST['phone'];
//If decition when user select other from the dropdown menu
if($Co_DEGREE == "other_degree") $Co_DEGREE = $Co_DEGREE_Other;
if($Co_CPOS == "other_cpos") $Co_CPOS = $Co_CPOS_Other;
if($Co_INST == "other_inst") $Co_INST = $Co_INST_Other;
if($Co_SCHOOL == "other_school") $Co_SCHOOL = $Co_SCHOOL_Other;
if($Co_DEPART_Other == "other_department") $Co_DEPART = $Co_DEPART_Other;
//This sets a starting point in the rollback process in case of errors along the code
$success = true; //Flag to determine success of transaction
//start transaction
echo "<br>1. Going to set autocommit to 0";
$command = "SET AUTOCOMMIT = 0";
echo "<br>2. Autocomint has been set to 0";
echo "<br>3. Going to run query to see if result is true or false";
$result = mysqli_query($con, $command);
echo "<br>4. Finished running the query. Result is:" . $result;
echo "<br>5. Going to set command to BEGIN";
$command = "BEGIN";
echo "<br>6. Command is now BEGIN";
echo "<br>7. Going to run query for command BEGIN";
$result = mysqli_query($con, $command);
echo "<br>8. Query runned for command BEGIN";
echo "<br>9. Result value is: " . $result;
//Saves Pi values into database
/**
$sqlCoPI = "INSERT INTO co_pi_table (Fname, Lname, SLname, Degree, Current_Position, Institution, School, Department, Program, Email, Phone)
VALUES('$Co_FNAME', '$Co_LNAME', '$Co_SLNAME', '$Co_DEGREE', '$Co_CPOS', '$Co_INST', '$Co_SCHOOL', '$Co_DEPART', '$Co_PROGRAM', '$Co_EMAIL', '$Co_PHONE')";
*/
echo "<br>10. Going to write sql command to populate table pi_table";
/**
$sqlPi = "INSERT INTO pi_table (Fname, Lname, SLname, Degree, Current_Position, Institution, School, Department, Program, Email, Phone)
VALUES('$Co_FNAME', '$Co_LNAME', '$Co_SLNAME', '$Co_DEGREE', '$Co_CPOS', '$Co_INST', '$Co_SCHOOL', '$Co_DEPART', '$Co_PROGRAM', '$Co_EMAIL', '$Co_PHONE')";
*/
$sqlPi = "INSERT INTO pi_table (Fname) VALUES('$Co_FNAME')";
//Checks to see if theres an error in the pi db con
echo "<br>11. Sql command finished writting.";
echo "<br>12. Going to query the sql finished command to the database to determine value of result.";
$result = mysqli_query($con, $sqlPi);
echo "<br>13. Finished running sql command to database. Result value is: " . $result;
echo "<br>14. Going to enter if statements depending on result value";
if($result == false){
//die ('<br>Error in query to PI table: ' . mysqli_error($con));
echo "<br>15. I am inside the false statement. Success is going to be set as false. ";
$success = false;
//$success = true; //Cahnged this in order to test if values are being saved to db. Change back to false.
}
//Checks for errors or craches inside the code
// If found, execute rollback
echo "<br>16. Going to verify is success is true.";
if($success){
$command = "COMMIT";
$result = mysqli_query($con, $command);
//echo "<br>Tables have been saved with 0 errors.";
echo "<br><p style=\"color: red;\"Principal Investigator has been saved successfuly. <br><br>
You may now CLOSE this page and press the<br><br> \"Refresh List\" <br><br>
button to display name in dropdown menu selection.</p>";
}
else{
$command = "ROLLBACK";
$result = mysqli_query($con, $command);
echo "<br>17. Success was determined to be false.";
echo "<br>Error! Databases could not be saved.<br>
Contact system manager to report error. <br> <br>" . mysqli_error($con);
}
echo "<br>18. Setting autocommit back to 1 again.";
$command = "SET AUTOCOMMIT = 1"; //return to autocommit
$result = mysqli_query($con, $command);
//Displays message
//echo '<br>Connection Successfully. ';
//echo '<br>Database have been saved';
//Close the sql connection to dababase
mysqli_close($con)
?>
As you can read, I am requiring users to fill out their information. Some of the information required are dropdown menu fields that user selects an option from among the presented ones.
The problem I am having is, when the above php code executes, it determines that the $result variable is false and doesn't save anything. When you execute the code, you get the following messages displayed:
1. Going to set autocommit to 0
2. Autocomint has been set to 0
3. Going to run query to see if result is true or false
4. Finished running the query. Result is:1
5. Going to set command to BEGIN
6. Command is now BEGIN
7. Going to run query for command BEGIN
8. Query runned for command BEGIN
9. Result value is: 1
10. Going to write sql command to populate table pi_table
11. Sql command finished writting.
12. Going to query the sql finished command to the database to determine value of result.
13. Finished running sql command to database. Result value is:
14. Going to enter if statements depending on result value
15. I am inside the false statement. Success is going to be set as false.
16. Going to verify is success is true.
17. Success was determined to be false.
Error! Databases could not be saved.
Contact system manager to report error.
18. Setting autocommit back to 1 again.
For security purposes I cant post the html content since it has sensitive name information nor the databases. Although I can ensure that the tables inside the database are called exactly as mentioned in the sql command line.
I HAVE FOUND THE PROBLEM!
After long debating I decided to recreate the database In which all the information was being stored. When I redirected the table in my sql command ( Instead of saving it in "pi_table" I saved it in a newly created database called "pi_table_2") and everything worked out properly.
Aparently my database got corrupted and phpMyAdmin didn't recognized that it was curropted.
For reference my database tables where in InnoDB format. What might have cause this to happen, who knows but if you ever encounter a similar problem, creating a small testing database and see if it saves. If it does, recreate the table and it might solve your issue like it solved mine.
Once again thank you a lot guys!!!!!
I am looking at the code and everything seems to be in order, could be a syntax error like a missing quotation for example:
//SQL code for connection w/ error control
$con = mysqli_connect("DB_HOST", "DB_USER", "DB_PASSWORD", "DB_NAME");
also
$db_selected = mysqli_select_db($con, "DB_NAME");
or die ("Cant select Database");
}
Hope this help.
Cheers;
Hasan
Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>
I simply don't get it.
I can connect fine to the Oracle database, but my account can only execute stored procedures. So I try to use one.
echo "before";
$nrows = '';
$stid = oci_parse($conn, 'begin :r := AR_INTEGRATIONS.F_SRVCIMPROVE_ACCNT_INCS(:p); end');
oci_bind_by_name($stid, ':p', '');
oci_bind_by_name($stid, ':r', $nrows);
if(!oci_execute($stid)){
$e = oci_error();
print htmlentities($e['message']);
exit;
}
echo "<br/>After";
When I load this on my browser, it's blank. But when I comment out the oci_bind_by_name() lines, it displays before but not after.
This is the first time I'm using PHP to connect to Oracle and execute queries. It's very different from just using MySQL.
What's going on?
$query = "SELECT `ip` FROM `banned` WHERE `ip` = '$ip'";
$retval = mysqli_query($conn, $query);
if(!$retval){
die("Could not Execute Query: " . mysqli_error($conn));
} else {
if(mysqli_num_rows($retval) == 0){
echo "test";
} else {
header('Location: http://www.teutonic-development.net/index.php?p=banned');
}
}
when I'm running this code all that's printed out is: "Could not Execute Query:"
I really have absolutely no idea why it's doing this. I'm connecting fine in my init.php file. Which is where this file is.
My other script which just adds a log entry works fine. And if I run my $query in phpmyadmin's sql interpreter it runs perfectly fine (when I replace the $ip part with an actual ip of course)
Any suggestions?
Normally one would say that hey your query failed to execute story finish. But this case is interesting.
Your code is
die("Could not Execute Query: " . mysqli_error($conn));
and your error message is
Could not Execute Query:
Notice even though you have mysqli_error($conn) but there is no mysql error being shown. That confirms 100% that $conn is not properly established (contrary to what you think)
So take a look at your code again and see if $conn is really a mysqli resource and is available to your file in proper variable scope.
I am attempting to insert some variables into MSSQL and its giving me a 500 server error
HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.
However it works when I substitute simple number or text values for those variables. I am running Wamp server and connecting to an amazon RDS MSSSQL instance. Here is my code:
$status = "closed";
$connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);
$query = "INSERT INTO DatabaseTableName (ColumnName) VALUES ('$status')";
$results = odbc_exec($connection, $query);
if ($results){
echo "Query Executed";
}else {
echo "Query failed " .odbc_error();
}
It works if I remove the variable $status and put in a number or a word instead. Any help would be greatly appreciated.
$query = "INSERT INTO DatabaseTableName (ColumnName) VALUES ('".$status."')";
You may want to look into cleansing your input as well.
See mysqli real escape string