trying to count entries in a database - php

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,

Related

Double while loop with sql query

I created a code that is working fine but I'm not sure if its 'legit'.
I am using a sql query in a while loop from another sql query, that means that the (second) sql query is repeated the amount of rows the first query returns.
Can anyone tell me if I can use this or its just one complete mess?
the code:
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql_feat = 'SELECT * FROM wp_wpl_dbst WHERE category = 105';
$result_feat = mysqli_query($conn, $sql_feat);
if (mysqli_num_rows($result_feat) > 0) {
while($row = mysqli_fetch_assoc($result_feat)) {
$filter_feat = $row["table_column"];
$filter_name = $row["name"];
$sql_feat2 = 'SELECT * FROM wp_wpl_properties';
$result_feat2 = mysqli_query($conn, $sql_feat2);
if (mysqli_num_rows($result_feat2) > 0) {
while($row2 = mysqli_fetch_assoc($result_feat2)) {
if (!empty($row2[$filter_feat])) {
echo $filter_name;
echo "<br>";
}
}
}
}
}
mysqli_close($conn);
First, you should always check the result of mysqli_query before assuming it represents a proper query result:
// you should check if this value is FALSE before using it
$result_feat = mysqli_query($conn, $sql_feat);
// and this too
$result_feat2 = mysqli_query($conn, $sql_feat2);
As for your code running a query inside the loop, it is pretty much always discouraged unless there is no other option. You should explore the possibility of a JOIN before running any queries inside a loop. Cases may exist where you have no other option, but in your code, I don't see any point at all to run this query over and over:
$sql_feat2 = 'SELECT * FROM wp_wpl_properties';
If it made reference to the value from $row, then maybe. But it doesn't.
Essentially you are doing dynamic sql so join would not be possible but adding where clause to second select would make it more efficient. something like - $sql_feat2 = 'SELECT ' + $filter_name + ' FROM wp_wpl_properties where ' + $row2[$filter_feat] + ' is not null';

Display Bids from database in order

Ive been trying to display a "bid" from the database to no success.
here is my error
Fatal error: Function name must be a string in /home/rslistc1/public_html/get-bids.php on line 7
here is my code
<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
$result3 = mysql_query($query3) OR die($mysql_error());
$num = mysql_num_rows($result3);
while ($row = mysql_fetch_array($result3, MYSQL_ASSOC)) { ?>
<?php echo''.$row['bid'].'';
}
?>
Any idea
Before we address the line 7 issue, lets check other errors. In order to request a query to a MYSQL database, we need to create a connection:
$con = mysqli_connect("ip_address","user","password","database_name");
Once we have that connection, let us check if we can actually connect to the database:
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
Appreciate that mysqli_error() function uses the connection. Now the query string:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
You are sending a query to look for a username called "$login_session" and it would most likely not find any match. To add strings from variables will be as follow:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '" . $login_session . "'";
Now, for the error in line 7
result3 = mysql_query($con, $query3) OR die($mysql_error($con));
As you can see, both mysql function use the connection to check for errors. Try it and let me know if everything works fine.
Edit:
Terribly sorry my friend, I just forgot to put a little letter "i" on the line, also, I would like to show you my way to deal with the query result. First, the line as it should be:
$result3 = mysqli_query($con, $query3);
Notice the i after mysql. Now let us check whether we got some rows or not:
if (!$result3) {
die('Could not retrieve data: ' . mysqli_error($con));
} else {
while ($row = mysqli_fetch_array($result3)) {
//Show your results
}
}

MySQL rows count with PHP and show result

I want to make an API that when you access it it will show result in text format of how many rows are on my database.
Database info:
Username: predator_db
DB Name: predator_db
Table Name: database
I tried a couple of codes and I could not get it to work.
Code tried:
<?php
$con = mysql_connect("localhost","predator_db","PASS");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("predator_db", $con);
$result = mysql_query("select count(1) FROM database");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>
Response Of Code: "Total Rows: " < Does not show how many rows. Error Log:
[05-Feb-2015 23:44:58 UTC] PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/predator/public_html/api/resolver/number.php on line 2
[05-Feb-2015 23:44:58 UTC] PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/predator/public_html/api/resolver/number.php on line 10
You're trying to fetch the results from database... not from your actual database of predator_db.
I'll do it with the basics, but please look into MySQLi prepared statements and/or PDO.
$link = mysqli_connect("localhost", "predator_db", "PASS", "predator_db");
$result = mysqli_query($link, "select COUNT(id) AS count FROM `database`");
// make sure it worked
if(!$result) {
die('Error: ' . mysqli_error($link));
} else {
$num_rows = mysqli_fetch_assoc($result);
// echo it
echo "Rows: " . $num_rows['count'];
}
First off, it's not a good idea to name a table after a reserved keyword like database. However, if you are going to go that route, you will always have to place the name in backticks ``. So, your query should be
$result = mysql_query("select count(1) FROM `database`");
Also, look into MYSQLi, as the old MySQL driver is deprecated.
<?php
$link = mysqli_connect("localhost", "DB_USER", "DB_PASS", "DB_NAME");
$result = mysqli_query($link, "select COUNT(*) AS count FROM DB_NAME.DB_TABLE");
if(!$result) {
die('Error: ' . mysqli_error($link));
} else {
$num_rows = mysqli_fetch_assoc($result);
echo "Rows: " . $num_rows['count'];
}
?>

no db connection but no error

here is my db connection code and query code:
// Connecting, selecting database
$link = mysql_connect('MySQLA22.webcontrolcenter.com', 'shudson', '*******')
or die('Could not connect: ' . mysql_error());
mysql_select_db('henrybuilt') or die('Could not select database');
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6";
$query = mysql_query($sql) or die ("Error");
There is no 'or die' error upon connecting, selecting, or querying
There is no error_log file
The sql query executes if I run it in my sql browser
What is going on???
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6"
Its missing ;
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6";
It appears correct...try adding this adapted code from the manual to further debug and see what you learn:
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($query)) {
echo $row['ID'];
echo $row['vcImageName'];
}

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