If I want to count one specific row (unread) in my database, how should i proceed with this MySQL query? As of now it counts the whole table.
$result_notifications = mysql_query("select count(1) FROM bhost_notifications where taker_id='$user_info[u_id]'");
$row_notifications = mysql_fetch_array($result_notifications);
$total_notifications = $row_notifications[0];
You need to alias the column.
SELECT COUNT(1) AS count ...
Then you would call $row_followers[count]. Be aware that mysql_ functions are deprecated. Learn about prepared statements when passing variables, and use PDO or MySQLi - this article will help you decide which.
I suspect you have an un-normalized database. While that is preferable in some situations, I doubt that they are in yours. As written you cannot be sure that the query will return the row you desire. SQL does not guarantee the order of rows, unless you use an order by clause.
It seems like this question indicates more problems the some syntax issues.
Over time I have written a nice function in PHP that allows me to easily look up records but still be dynamic enough to be useful in every type of query that I perform.
Usage:
if (get("select * from table", $query_array) > 0)
{
// There is at least one row returned
$result_array = mysql_fetch_array($query_array);
.
.
.
} else {
// No rows in the set
}
Function:
function get($sql, &$array)
{
$array = "";
$q = mysql_query($sql);
if (mysql_error())
{
$ret = -1;
print "<div><font style='font-family: arial; font-size: 12px;'><font style='color: red;'>Error:</font> " . mysql_error() . "<br>SQL: #sql</font></div>";
exit(1);
} else {
$ret = mysql_num_rows($q);
if ($ret > 0)
{
$array = $q;
}
}
return $ret;
}
This also gives a formatted error message in the case that there is something wron with the query. I use this all the time because it compresses the mysql_query and mysql_num_rows together into a single command.
Related
So I am trying to echo out how many rows there are in a table with a COUNT command, but I purposely have no rows in the table right now to test the if statement, and it is not working, but worst, it makes the rest of the site not work(the page pops up but no text or numbers show up on it), when I added a row to the table, it worked fine, no rows = no work. Here is the piece of the code that doesn't work. Any and all help is highly appreciated.
$query1 = mysql_query("
SELECT *, COUNT(1) AS `numberofrows` FROM
`table1` WHERE `user`='$username' GROUP BY `firstname`,`lastname`
");
$numberofrowsbase = 0;
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
$enteries1 = $enteries1;
}else{
$enteries1 = $numberofrowsbase;
}
echo enteries1;
}
Seems you have over complicated everything. Some good advise from worldofjr you should take onboard but simplest way to get total rows from a table is:
SELECT COUNT(*) as numberofrows FROM table1;
There are several other unnecessary lines here and the logic is all bonkers. There is really no need to do
$enteries1 = $enteries1;
This achieved nothing.
Do this instead:
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
echo $row['numberofrows'];
}
}
Maybe against my better judgement, I'm going to try and give you an answer. There's so many problems with this code ...
Do Not Use mysql_
The mysql_ extension is depreciated. You should use either mysqli_ or PDO instead. I'm going to use mysqli_ here.
SQL Injection
Your code is wide open to SQL injection where others can really mess up your database. Read How can I prevent SQL injection in PHP? for more information.
The Code
You don't need to count the rows with a SQL function, especially if you want to do something else with the data you're getting with the query (which I assume you are since you're getting a count on top of all the columns.
In PHP, you can get how many rows are in a result set using a built in function.
So all those things together. You should use something like this;
// Connect to the database
$mysqli = new mysqli($host,$user,$pass,$database); // fill in your connection details
if ($mysqli->connect_errno) echo "Error - Failed to connect to database: " . $mysqli->connect_error;
if($query = $mysqli->prepare("SELECT * FROM `table1` WHERE `user`=?")) {
$query->bind_param('s',$username);
$query->execute();
$result = $query->get_result();
echo $result->num_rows;
}
else {
echo "Could not prepare query: ". $mysqli->error;
}
The number of rows in the result is now saved to the variable $result->num_rows, so you can use just echo this if you want, like I have in the code above. You can then go onto using any rows you got from the database. For example;
while($row = $result->fetch_assoc()) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo "$firstname $lastname";
}
Hope this helps.
If I have to query db and do something one the basis of number of rows , in mysql I simply query and I can simply query and use simply
if($result->num_rows >= 1){
but in PDO
I have to
make count query , the use fetchCloumn() to get count
query again to get the same result and do whatever I want
Rowcount is not helpful , it doesn't work on select
so I am making query twice, PDO doesn't sounds to be helpful here, is my approach wrong or I am right?
Thanks
IMHO, counting all the rows returned by the query (or issue a second query) just to find out if there are rows or not is kind of overkill.
$got_data = false;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$got_data = true;
process_row($row);
}
if (!$got_data) {
no_results();
}
If you do need the rowcount, it's trivial to get it while reading the result set:
$num_rows = 0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$num_rows++;
process_row($row);
}
if ($num_rows==0) {
no_results();
}
YMMV.
i'm trying to make a long mysql query and process and update the row founded:
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
$result = mysql_query($query);
$total = mysql_num_rows($result);
echo $total;
while ($db_row = mysql_fetch_assoc($result))
{
//process row
}
but after 60 second give me a timeout request, i have try to insert these in my php code:
set_time_limit(400);
but it's the same, how i can do?
EDIT:
only the query:
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
takes 2-3 second to perform, so i think the problem is when in php i iterate all the result to insert to row or update it, so i think the problem is in the php, how i can change the timeout?
EDIT:
here is the complete code, i don't think is a problem here in the code...
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
$result = mysql_query($query);
$total = mysql_num_rows($result);
echo $total;
while ($db_row = mysql_fetch_assoc($result)) {
//print $db_row['id_show']."-".$db_row['actors']."<BR>";
$explode = explode("|", $db_row['actors']);
foreach ($explode as $value) {
if ($value != "") {
$checkactor = mysql_query(sprintf("SELECT id_actor,name FROM actors WHERE name = '%s'",mysql_real_escape_string($value))) or die(mysql_error());
if (mysql_num_rows($checkactor) != 0) {
$actorrow = mysql_fetch_row($checkactor);
$checkrole = mysql_query(sprintf("SELECT id_show,id_actor FROM actor_role WHERE id_show = %d AND id_actor = %d",$db_row['id_show'],$actorrow[0])) or die(mysql_error());
if (mysql_num_rows($checkrole) == 0) {
$insertactorrole = mysql_query(sprintf("INSERT INTO actor_role (id_show, id_actor) VALUES (%d, %d)",$db_row['id_show'],$actorrow[0])) or die(mysql_error());
}
} else {
$insertactor = mysql_query(sprintf("INSERT INTO actors (name) VALUES ('%s')",mysql_real_escape_string($value))) or die(mysql_error());
$insertactorrole = mysql_query(sprintf("INSERT INTO actor_role (id_show, id_actor, role) VALUES (%d, %d,'')",$db_row['id_show'],mysql_insert_id())) or die(mysql_error());
}
}
}
}
Should definitely try what #rid suggested, and to execute the query on the server and see the results/duration to debug - if the query is not a simple one, construct it as you would in your PHP script, and only echo the SQL command, don't have to execute it, and just copy that in to the server MySQL command line or whichever tool you use.
If you have shell access, use the top command after running the above script again, and see if the MySQL demon server is spiking in resources to see if it really is the cause.
Can you also try a simpler query in place of the longer one? Like just a simple SELECT count(*) FROM tvshows and see if that also takes a long time to return a value?
Hope these suggestions help.
There are so many problems with your code.
Don't store multiple values in a single column. Your actors column is pipe-delimited text. This is a big no-no.
Use JOINs instead of additional queries. You can (or could, if the above weren't true) get all of this data in a single query.
All of your code can be done in a single query on the server. As I see it, it takes no input from the user and produces no output. It just updates a table. Why do this in PHP? Learn about INSERT...SELECT....
Here are some resources to get you started (from Googling, but hopefully they'll be good enough):
http://www.sitepoint.com/understanding-sql-joins-mysql-database/
http://dev.mysql.com/doc/refman/5.1/en/join.html
http://dev.mysql.com/doc/refman/5.1/en/insert-select.html
What is Normalisation (or Normalization)?
Let me know if you have any further questions.
Simple question I guess, but a fundamental one and I'm not sure of the best practice.
So let's say that I have a database with some IP addresses that I want to display to the user.
Is this a good/secure way/practice?
//--> CONNECT TO DB, etc
$db_query = 'SELECT ip,'
."FROM table "
."GROUP BY ip ";
$result = $db_conn->query($db_query);
echo 'Found '.$result->num_rows.' records';
if($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQLI_BOTH))
{
//POPULATE A HTML TABLE/WHATEVER WITH THE INFO
}
}
I'm mostly concerned about this: $result->num_rows > 0 and this: fetch_array(MYSQLI_BOTH)
I'm asking because I read somewhere that num_rows > 0 can usually mean trouble depending on the situation, for example a user login. In that case I suppose it would num_rows == 1 right?
And also, I haven't fully understood the difference between MYSQLI_BOTH and other forms of fetching.. If you could simple explain them to me and when to use them I would be grateful.
What do you think?
I would add a check to ensure your query was executed OK - and if not output the error :
$result = $db_conn->query($db_query);
// check for error - output the error
if (!$result) {
$message = 'Invalid query: ' . mysqli_error() . "\n";
$message .= 'Whole query: ' . $db_query;
die($message);
}
echo 'Found '.$result->num_rows.' records';
Other than that ... looks OK
EDIT:
To explain MYSQLI_BOTH, the options are MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH ->
MYSQLI_ASSOC = Associative array so the value of the rows can be accessed using $row['column']
MYSQLI_NUM = Numeric array so the values of the rows are accessed using a number $row[n] where n is the number of the column (0 based)
MYSQLI_BOTH = can use both to access values of row either $row[n] or $row['column']
EDIT2:
There is also a function for checking the number of returned rows :
if(mysqli_num_rows($result) == 0){
echo "Sorry. No records found in the database";
}
else {
// loop you results or whatever you want to do
}
EDIT3:
php.net has some excellent docs for the MY_SQLI extension
Two things:
If you only need an associative array, then don't use fetch_array(). Use fetch_assoc().
There's no need to concatenate the query like that, you could use something like:
$sql = "
SELECT
ip
FROM
table
";
This helps with large queries with multiple options in the WHERE clause or JOINs. It's quicker to type out, and you can quickly copy and paste it for checking in phpMyAdmin and the like.
A while ago I was poking around with SQLite, trying to port some of my sites to use it instead of MySQL. I got hung up on the lack of a function to count results, like PHP's mysql_num_rows(). After searching a little I discovered this mail list, which says (as I understand it) that SQLite doesn't have that functionality because it's inefficient. It states that it is bad form to write code that needs to know how many rows are returned.
I generally use mysql_num_rows to check for empty return results. For example:
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if (mysql_num_rows($results)) {
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
}
} else {
echo "<p>No results found</p>";
}
The vehement distaste for the concept of mysql_num_rows() in the SQLite community makes me wonder if it's that terribly efficient for regular MySQL in PHP.
Is there a better, more accepted way for checking the size of a MySQL result set in PHP besides mysql_num_rows()?
EDIT:
I'm not just using mysql_num_rows to get the count--I would use a COUNT query for that. I'm using it to check if there are any results before outputting everything. This is useful for something like displaying search results - it's not always guaranteed that there will be results. In SQLite world, I have to send one COUNT query, check if there is something, and then send a SELECT query to get everything.
You already have something that is telling you if you've got results in mysql_fetch_array(). It returns false if there are no more rows to fetch (from php.net).
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if($results) {
$row = mysql_fetch_array($results);
if($row) {
do {
echo "<p>{$row[whatever]}</p>";
} while($row = mysql_fetch_array($results));
} else {
echo "<p>No results found</p>";
}
} else {
echo "<p>There was an error executing this query.</p>";
}
Regardless of whether or not you actually use what you SELECTed, all of the rows are still returned. This is terribly inefficient because you're just throwing away the results, but you're still making your database do all of the work for you. If all you're doing is counting, you're doing all that processing for nothing. Your solution is to simply use COUNT(*). Just swap COUNT(*) in where you would have your SELECT statement and you're good to go.
However, this mostly applies to people using it as a complete substitute for COUNT. In your case, the usage isn't really bad at all. You will just have to manually count them in your loop (this is the preferred solution for SQLite users).
The reason being is in the underlying SQLite API. It doesn't return the whole result set at once, so it has no way of knowing how many results there are.
As explained on the mailing list you found. It is inefficient to return the count of rows because you need to allocate a lot of memory to hold the entire (remaining) result set. What you could do, is to simply use a boolean to test if you have output anything.
$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
$empty_result = true;
while ($row = mysql_fetch_array($results)) {
echo "<p>$row[whatever]</p>";
$empty_result = false;
}
if ($empty_result) {
echo "<p>No results found</p>";
}