PHP MySQL Query Returning Rows Very Slow - php

I am having a problem with a MySQL query. When ever I run this query it takes over 10 seconds to return the rows. However if I change my limit to 29 it returns it in less than 1 second. My Question is my implementation and query in good shape, or am I making a mistake here that would cause this issue?
<?
try
{
$con = mysql_connect("XXX.XXX.XXX.XXX","XXX","XXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bis_co", $con);
$query = "SELECT Name, Value FROM `bis_co`.`departments` LIMIT 31";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
while($row = mysql_fetch_assoc($result)){
echo $row['Name'] . "<br />";
}
mysql_close($con);
}
catch(Exception $e)
{
echo $e;
}
?>

You could try getting rid of the
$row = mysql_fetch_array($result)
statement. The if statement will take care of returning the array. You could also change the query string to
"SELECT Name, Value FROM `departments` LIMIT 31"
since you're already setting the database name in the mysql_select_db statement. Though, none of these should be causing your issues. It seems like it's a table issue. Have you tried it with mysqli and prepared statements?

Related

Simple PHP MySQLi script fails to run

I have this same query running on other PHP scripts, but it now won't work. I have troubleshooted for eight hours and frustrated like no one knows.
<?php
$con = mysqli_connect("localhost","dave1_guest","password1")
or die('Could not connect: ' . mysqli_error());
mysqli_select_db("dave1_main",$con) or die(mysqli_error());
$result = mysqli_query("SELECT * FROM Inventory limit 100");
while($row = mysqli_fetch_array($result)) {
echo $row['ItemNumber'];
}
mysqli_close($con);
?>
I tried running the query on PhpMyAdmin, and it returns 0 results! This is impossible. When I open the table with PhpMyAdmin, it opens and shows thousands of rows!
When I run the query that PhpMyAdmin uses, it works. But when I add a constraint like WHERE StockNumber='13922', it does not.
Again, the stupid thing is that this script works on other PHP pages on my site.
You are fetching the data twice. Remove this line $row = mysqli_fetch_array($result);
I do not know what your problem, so I do not see the exact error, but I'll try a little help.
First of all:
$con = mysqli_connect("localhost","dave1_guest","password1") or die('Could not connect: ' . mysql_error());
mysqli_select_db("dave1_main",$con) or die(mysql_error());
$result = mysqli_query("SELECT * FROM Inventory LIMIT 100");
$row = mysqli_fetch_assoc($result);
print_r($row);
while($row)
{
echo $row['ItemNumber'];
}
mysqli_close($con);
Try this!

trying to count entries in a database

I'm trying to count entries in a database based on 2 basic criteria. It is returning a blank result, even though there are results to be found. Anyone have any idea what I am doing wrong here? I have tried it so many different ways and they all return no result. (If I enter the query directly in phpmyadmin it returns a result.)
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
$numericalResult = mysql_query($sql, $con);
$row = mysql_fetch_object($numericalResult);
$totalOrders1 = $row->total_count;
echo "My orders:" . $totalOrders1;
As others stated, make sure you sanitize variables before they go into query.
$sql = "SELECT * FROM orderOption3Detail WHERE orderDate = '" . $orderDate . "' AND studentID = '" . $studentID . "'";
$sql_request_data = mysql_query($sql) or die(mysql_error());
$sql_request_data_count = mysql_num_rows($sql_request_data);
echo "Number of rows found: " . $sql_request_data_count;
That's all you need.
Edited: providing full code corrected:
$con=mysqli_connect($db_host,$db_user,$db_pass,$db_name); // Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //global option 1
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
//echo $sql;
$numericalResult = $con->query($sql);
$row = mysqli_fetch_object($numericalResult);
echo $row->total_count; //echo (int) $row->total_count;
Please test this and let me know. Good luck!
----- End Editing ----
Have you tested assigning values directly as a test in your SQL string, like:
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='05/23/2012' AND studentID='17'";
Also, did you check if the date's format is correct, reading that $orderdate variable and testing it in PHPMyAdmin?
Did you read the $sql with values inserted and test in PHPMyAdmin and worked?
Also, check the connection to assure there is no problem there.
One more thing, sorry. You seem to be using the wrong syntax in your mysql_query statement. That way works for mysqli_query, and the parameters would be inverted. Try only:
$numericalResult = mysql_query($sql);
Provided you made the connection and database selection previously, like in:
$connection=mysql_connect($db_host, $db_username, $db_password);
if (!$connection)
{
$result=FALSE;
die('Error connecting to database: ' . mysql_error());
}
// Selects database
mysql_select_db($db_database, $connection);
Best wishes,

Using PHP to pull data from MySQL table column randomly

I am using the following (assume I already plan to change these to mysqli at a later date and am aware of the insecurity of the queries used), to pull text strings from rows in one column in a MySQL table and the output in a browser would, ideally, be a randomly selected string from this column:
mysql_connect($host,$username,$password);
mysql_select_db($database) or die(mysql_error ());
$query="SELECT * FROM `tablename` ORDER BY RAND() LIMIT 0,1;";
$result=mysql_query($query);
$rows = array();
while($row = mysql_fetch_array($rs)) {
$rows[] = $row;
}
mysql_close();
$max = count($rows) - 1;
Using the following echo line to achieve the last bit in the browser:
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4]$
?>
I receive the error "PHP Notice: Undefined offset: 0 in script.php on line 19" in reference to this echo line (which, admittedly, was pieced together from other threads and tutorials, so I do not follow completely), however, I've since resolved all other errors logged and observed, so if possible, how can I amend this so the output is just a single row (the text within it) from the column?
Faster and better than using RAND()
$conn = mysqli_connect($host,$username,$password, $database);
if($conn->connect_errno > 0) {
die('Unable to connect to database [' . $conn->connect_error . ']');
}
$total_rows = 20; //Generate Random number. You could get $total_rows with a first query counting all rows.
$selected_row = mt_rand(0, $total_rows);
//$selected_row -= 1; //just in case you randomized 1 - $total_rows and still need first row.
//Use the result in your limit.
$query="SELECT * FROM `tablename` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["columnname"];
}
Edit it from mysql to mysqli (on the fly). You would not want to use RAND() if your table is very large. Believe me!
In your SELECT-statement, you are telling the database to order the strings randomly. So just get the first one and echo it:
$row = mysql_fetch_array($rs)
echo $row['name_of_field_you_want_to_echo'];
You never define the variable $rs. Other than that...
If you are selecting the first items from a SQL query, you don't need to specify both the limit and top.
$result = mysql_query("SELECT * FROM `tablename` ORDER BY RAND() LIMIT 1");
Since that will ever return one row, you can use mysql_fetch_row
$row = mysql_fetch_row($result);
and then you can get the field from that row with
echo $row["column_name"];

Can't get results from mySQL query to display in PHP

I am very new to PHP and can't seem to use mySQL data at all from PHP. The SQL query I wrote works fine in phpMyAdmin when I run it in the SQL editor, but the most I am able to get from the code is the following from var_dump. Nothing else displays anything at all.
resource(3) of type (mysql result)
Any help at all would be greatly appreciated!!
<?php
ini_set(‘display_errors’,1);
error_reporting(E_ALL|E_STRICT);
$con = mysql_connect("localhost","XXXXXXXX","XXXXXXX");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sharetrader", $con);
$sharelist = mysql_query("SELECT DISTINCT tblStocks.stockSymbol, tblShareData.lookupDate FROM tblStocks LEFT JOIN tblShareData ON tblShareData.tickerCode = tblStocks.stockSymbol ORDER BY tblShareData.lookupDate ASC LIMIT 0 , 30");
if (!$sharelist) {
die('Invalid query: ' . mysql_error());
}
var_dump($sharelist);
while ($row = mysql_fetch_array($sharelist)) {
echo $row['tblStocks.stockSymbol'];
}
mysql_close($con);
?>
I am very new to PHP
But you're making great progress - just missing some of the finer points.
try:
while ($row = mysql_fetch_array($sharelist)) {
var_dump($row);
}
...and it should be obvious what's happening.

SQL Multiple Update Statements

I need to update 40 rows in a database, starting at the point where the userID is a match. I do not want to have to determine the row number because eventually this database will be huge.
What I would like to do is simply say:
"Update these the next 40 rows with my array where userID = myUserID"
Here is what I have:
<?php
// connect to the database and select the correct database
$con2 = mysql_connect("localhost","Database","Password");
if (!$con2)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ifaves_code", $con2);
$i = 0;
while ($i < 40) {
//cycle through the array
$cycleThrough2 = $updatedUserNames[$i];
//$query = "UPDATE tblUserLinks SET `URLName` = '$cycleThrough2' WHERE userID = '" . $mainUID . "' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
++$i;
}
mysql_close();
?>
The variable $mainUID is being set correctly, the problem I'm having is it appears there are no updates taking place in the database.
How can I alter my existing code to receive my desired behaviour?
I don't suppose it's because you have your query building statement commented out...
//$query = "UPDATE tblUserLinks SET `URLName` = '$cycleThrough2' WHERE userID = '" . $mainUID . "' LIMIT 1";
If this is just the result of debugging and it wasn't working before that, you must call mysql_error() right after mysql_query() to see why it is failing.
$result = mysql_query($query);
if (!$result) echo mysql_error();
Also, you are using LIMIT 1 at the end, but the userID never changes in the WHERE clause. Therefore, you are updating the same row over and over 40 times on each loop. What you need is a way in your WHERE clause to identify rows which have already been modified, and exclude them. Otherwise, the same row (first match) will always be caught by the LIMIT 1 and updated.

Categories