We have a website that accesses a SQL Server 2005 server for one query. Currently, the site is in ASP, we are moving it to PHP, and the PHP one is currently being tested. After we run a few successful queries on the PHP site, it returns the "Error in database query. Please try again later" line in the code below. When I rewrote that line with sqlsrv_errors to elaborate, it told me that the table didn't exist. There are about 40 tables in the database, but after the error happens it only shows 8 of them in Management Studio. However, if I allow it to sit for about 5 minutes, all of the tables are restored. No matter how many times the old ASP site is used, the table does not do this. However, when the tables disappear from using the new site, the old site shows inaccessible for a few minutes until the tables re-appear in SQL Server management studio. I didn't see any kind of connection limits on the SQL Server, so I don't know whether it's something I'm doing in the PHP SQL queries or within the SQL Server properties.
<?php
include ("dbvals.inc.php");
if (!empty($_POST['lastnamebox'])) {
$dbhandle = sqlsrv_connect($dbServer, $connectioninfo);
if($dbhandle == false){
echo "Error connecting to database. Please try again later. ";
}
else{
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
$params = array();
array_push ($params, $_POST['lastnamebox']);
$results = sqlsrv_query($dbhandle, $query, $params);
if($results == false){
echo "Error in database query. Please try again later.";
//This is printed when database tables temporarily disappear
}
else
{
$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
if($row){
do{
echo "<tr><td class='tablecell'>";
echo $row['LastName'] . "," . $row['FirstName'] . "<br>";
echo "Address: " . $row['Address'] . "<br>";
echo "City, State, Zip: " . $row['CSZ'] . "<br>";
echo "</tr></td'>";
}while($row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC));
}
else{
echo "No results found. Please try another query.";
}
}
}
sqlsrv_free_stmt($results);
sqlsrv_close($dbhandle);
}
else {
echo "Please type a value in the search box.";
}
?>
The $query is wrong to begin with. Change it to:
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
Not sure about the tables disappearing though. What driver are you using?
Just another issue I'm seeing with the code not sure if it's related to your problem. or another copy error but here it is.
if ($r1 = sqlsrv_fetch_array($results)) {
while( $row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC)){
The first fetch should also have '($results,, SQLSRV_FETCH_ASSOC)'
Additional that check is going to eat the first returned record which may or may NOT be what you intended.
Also it is possibly that PHP seeing some results in the while as false even though they aren't and the server is still waiting on you to finish getting the rest. Seen code like that cause 'Server has got away' errors in MySQL which could be what is going on here as well.
Not sure of the syntax but a sqlsrv_clode_cursor() just before the connection close might also fix your issue if there's some kind of connection polling going on. Could be simply running out of connection or getting old one in a incorrect state.
SELECT * FROM Person WHERE AND LastName LIKE
Looks like there something missing between the WHERE and AND to me.
I don't know SQL Server really so it could allow that but it's not standard SQL. Depending on how it's reacting to that error I could see it 'Going away' so to say and reporting tables missing.
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
I have a problem with my PHP code.
I am trying to make a level create function for a small game project me and another person are working on.
My code works.. but generates a lot of duplicates.
Here's the code: (Don't laugh at me for how vulnerable this is, this will be fixed eventually, THIS IS JUST TEST CODE AND WILL NEVER BE ON A PUBLIC SERVER IN ANY CIRCUMSTANCE, OK?)
$mysqli = new mysqli("localhost", "Username", "Password", "sys");
$SqlQuery = "INSERT INTO levels (levelname, levelauthor, leveldata)
VALUES(\"" . $_GET["levelName"] . "\", \"" . $_GET["levelAuthor"] . "\", \"" . $_GET["levelData"] . "\");";
$query2 = "SELECT * FROM levels WHERE leveldata = \"" . $_GET["levelData"] . "\";";
//echo "SELECT * FROM levels WHERE leveldata = \"" + $_GET["levelData"] + "\";";
$uresult = $mysqli->query($SqlQuery, MYSQLI_USE_RESULT);
$res2 = $mysqli->query($query2, MYSQLI_USE_RESULT);
if ($uresult) {
while ($row = $res2->fetch_assoc()) {
//This should always work. Lol
echo "(SUC)|ID:" . $row["levelid"];
}
}
After running this code, I expected to just check my database and be able to see the test I wrote, without duplicates.
I started the PHP development server and went to:
http://localhost/Create.php?levelName=PHPTest&levelAuthor=Test3&levelData=[snip]
I expected to see something along the lines of "(SUC)|ID:4" (there were 3 entries in the database at the time), but I saw this:
(SUC)|ID:4(SUC)|ID:5(SUC)|ID:6(SUC)|ID:7(SUC)|ID:8(SUC)|ID:9(SUC)|ID:10(SUC)|ID:11
This was unexpected. I thought it was just an error in my code (keep in mind, the last one had a broken ID grabbing system, but worked), and that it would work, but then, I went to check the database, and saw a ton of duplicates with the same data.
Does anyone know how to fix this code?
Obvious question but autocommit is enabled on database?
Do you have some open transaction?
Use this to check open transactions on MySQL.
Alright. I have searched and searched for an answer, but I just could not find it.
I am writing a simple php script that takes the url information and runs it through a MySQL query to see if a result comes up. I try to echo the variable holding the query out, but nothing shows up. I know there must be a result because if I enter the query manually in MySQL it displays my desired result.
$result = mysqli_query("SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
I have tried to echo out both the $result and $data. But there is nothing displayed. I am so new to programming, and this is my first StackOverflow post, so forgive me if I am making huge errors.
Actually mysqli_query() requires two parameters... check the following sample example ..
<?php
$conn = mysqli_connect('localhost','root','','your_test_db');
$_GET['page'] = 1;
$result = mysqli_query($conn,"SELECT * FROM your_table WHERE id = '" . $_GET['page'] . "'");
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
?>
As you have stated you are just in a learning phase, it is okay to code these sort of queries just to learn yourself but do not code these kind of queries as these queries are vulnerable so i would suggest you to use prepare queries or PDO...
Also never use SELECT * in your queries, this is a bad practice, only deal with the fields which you requires in return.
Also, you can always check whether your database is connected or not. So that you have a better idea.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
you have not mentioned whether you are following OOP structure or not .. so i would suggest you to check error_reporting() and connect database on the same page to check the things around ..
Also you can check whether you without WHERE condition for now "SELECT * FROM your_table just to make sure whether you are getting atleast all the records or not.
The problem is that you're not setting up the connection in the query. mysqli_query() requires two parameters.
Make the connection first:
$conn = mysqli_connect("localhost", "user", "password", "dbname");
Now execute the query:
$result = mysqli_query($conn,"SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
NOTE: Your code is heavily vulnerable to MySQL injections. Use MySQLi or PDO Prepared statements.
Also, you should use mysqli_errno() to find out your query bugs.
Edit:
Also do this:
while($row=mysqli_fetch_assoc($result)){
//do the result output.
}
I have code here that is supposed to print a html table from my mysql database. When I open the page in my web browser, it is a blank page.
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'admin', 'may122000');
mysql_select_db('contacts');
$query = "SELECT * FROM users";
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
echo "</table>";
mysql_close();
?>
</body>
</html>
Remove password
Enable error output
When you use mysql_fetch_array you will get the resulting array with numeric indices.
mysql_fetch_assoc will give you an associative array, like you want.
Note: mysql_* is deprecated.
while($row = mysql_fetch_assoc($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
If you still want to use mysql_fetch_array you'll have to pass a second parameter:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
First of all user mysqli or PDO and mysqli_fetch_assoc() so you have only associative array. Blank page is probably result of a hidden error, that's stored in your error.log on your server - take a look at it and get back to us.
I prefer using PDO or mysqli but anyway , Are u sure Your connection is established ? to check this and check other connections and query :
if (!connection)
die(mysql_error());
try this and feedback me
Improvements - some of which already mentioned in other post but all put together in one form:
<?php
$connection = mysqli_connect('localhost', 'admin', '****', 'contacts');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT first_name, last_name, phone FROM users";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
echo "<table>"; // start a table tag in the HTML
while($row = mysqli_fetch_array($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
echo "</table>";
mysqli_close($connection);
?>
So, first off the MySQL_* has been upgraded to Mysqli, with some minor reformatting,
The select * has been replaced with selecting only the needed columns.
The closing statement has been correctly set.
Firstly if your connection fails an error catch will output this to the screen. Remove this upon product launch or public launch of the page.
A (Rather rudimentary) error catch has been put in that if the SQL Query is bad that an error is outputted. Again, this should be removed in production but will help you with finding SQL errors.
If No SQL errors return the you have either an empty table in your database, or some sort of PHP error but from the code sample given the most likely error is that your PHP doesn't run MySQL and would only run PDO or MySQLi.
You also said "when I open the page in my browser it is a blank page", if the Source of the page is blank - as in it DOES NOT show
<html>
etc, then this is a sign the PHP execution failed and you have bad PHP, as detailed in your error log file.
The most likely cause of this from the code sample given is, as stated already, your PHP version does not support MySQL.
If your
<table>
Tag appears in your HTML source code then this is a sign that the While clause is not running which means your Datbase table is empty and there is no data to output.
Hope this helps. But first point of call is to upgrade to MySQLi :)
Ok, I'm following a youtube guide on how to create a very simple blogging system using PHP/MySQL as I'd like to get to learn these 2 languages a bit more. I'm creating this in my localhost, permissions set-up correctly.
The problem is, when I go onto localhost/tables.php, it comes up as white screen which it's supposed to, but it's not creating the relevant tables within the database?
Here's the code I'm using:
mysql.php
<?php
mysql_connect('localhost','username','password'); //where localhost is the host, username is the relevant username and password is the relevant password.
mysql_select_db('database'); //where database is the chosen database in which to drop the tables.
?>
tables.php
<?php
include "mysql.php";
$table = "ENTRIES";
mysql_query ("CREATE TABLE IF NOT EXISTS `$table` (`ID` INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( `id` ) )");
mysql_query ("ALTER TABLE `$table` ADD `TITLE` TEXT NOT NULL");
mysql_query ("ALTER TABLE `$table` ADD `SUMMARY` TEXT NOT NULL");
mysql_query ("ALTER TABLE `$table` ADD `CONTENT` TEXT NOT NULL");
?>
Nothing is appearing in the error log which is frustrating and not helping me diagnose the problem.
Any help would be much appreciated! Thanks.
As you have no errors run this code to show if you have created created the table ENTRIES.
<?php
include "mysql.php";
$result = mysql_query("SHOW COLUMNS FROM `ENTRIES`");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
?>
NOTE As you are starting with MySQL you would be advised to use PDO in place of the deprecated mysql_.
Here is a good tutorial
EDIT
Following comments the following code lists databases and tables on server(Note uses deprecated mysql_ function).
Ensure that the proper parameters replace "XXX".
<?php
$host= "localhost";
$username="XXX";
$password="XXX";
$database="XXX";
$link = mysql_connect($host,$username,$password); //where localhost is the host, username is the relevant username and password is the relevant password.
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
echo "<BR>";
}
echo "<BR>";
$result = mysql_list_tables($database);
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
echo "Table: ", mysql_tablename($result, $i), "\n";
echo "<BR>";
}
?>
Nothing is appearing in the error log which is frustrating and not helping me diagnose the problem
So your first poblem is to find out why it's not logging any errors. BTW it would also be a good idea to inject some echo / print statements to find out where it's failing.
Forget about the MySQL stuff and try:
<?php
trigger_error("Testing", E_USER_WARNING);
?>
Even though (once you've got the error reporting sorted out) you should get an error logged it will likely only contain a limited amount of information. Any time you call a mysql function, be via mysql_, mysqli or PDO, you should poll the return value and handle any error - even if it's just to echo the value to the screen.
It's saying that I haven't selected a database
Possibly the user account you are connecting as does not have permission to access the database.