I am troubleshooting this query that I was previously trying to use to count rows but now I have discovered that 0 rows are being found in the database even though they exist. I have checked previous queries I have used and they work and look the same. The $db_conx definitely works to connect to the database as I am using it on other web pages. Does any one have any suggestions? Thanks
$result =("SELECT * FROM Request WHERE user2='joey' AND accepted='0'");
$query = mysqli_query($db_conx, $result);
$rows = mysqli_num_rows($query);
if (rows < 1) {
echo '<strong style="color:#F00;">No rows</strong>';
exit();
} else {
echo '<strong style="color:#F00;">Rows exist</strong>';
exit();
}
You are missing an important step to select something from the database and that is what are you trying to select. And, you are also missing the $ in the rows.
$result =("SELECT something FROM Request WHERE user2='joey' AND accepted='0'");
$query = mysqli_query($db_conx, $result);
$rows = mysqli_num_rows($query);
if ($rows < 1) {
echo '<strong style="color:#F00;">No rows</strong>';
exit();
} else {
echo '<strong style="color:#F00;">Rows exist</strong>';
exit();
}
You edited your original post https://stackoverflow.com/revisions/33307758/1
being SELECT FROM Request
You have selected "nothing" from your query
SELECT FROM ...
Read the manual on SELECT:
https://dev.mysql.com/doc/refman/5.0/en/select.html
and this if (rows < 1) { - rows is treated as a constant instead of a variable.
Error reporting would have told you that if it was setup to catch and display on your system.
if ($rows < 1) {
and make sure you are successfully connected to your db using the same MySQL API as your query.
Check for errors on your query
http://php.net/manual/en/mysqli.error.php
Look into using a prepared statement also.
https://en.wikipedia.org/wiki/Prepared_statement
Nota:
You will also need to escape your data should it be coming from user input at one point.
I.e.:
$var = $_POST['var'];
and if $_POST['var'] is equivalent to joey's bistro.
MySQL will see that as WHERE user2='joey's bistro' if it were passed as a variable in the query WHERE user2='$var' resulting in a syntax error.
Escaping it will render it as joey\'s bistro being valid syntax.
$var = mysqli_real_escape_string($db_conx,$_POST['var']);
This would be beneficial for just that as well as helping to protect against an SQL injection.
https://en.wikipedia.org/wiki/SQL_injection
Related
My query is not working when I use the variable in the WHERE clause. I have tried everything. I echo the variable $res, it shows me the perfect value, when I use the variable in the query the query is not fetching anything thus mysqli_num_rows is giving me the zero value, but when I give the value that the variable contains statically the query executes perfectly. I have used the same kind of code many times and it worked perfectly, but now in this part of module it is not working.
Code:
$res = $_GET['res']; // I have tried both post and get
echo $res; //here it echos the value = mahanta
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'"; // Here it contains the problem I have tried everything. Note: restaurant name is same as it is in the database $res contains a value and also when I give the value of $res i.e. mahanta in the query it is then working.
$z = mysqli_query($conn, $query);
$row2 = mysqli_fetch_array($z);
echo var_dump($row2); // It is giving me null
$num = mysqli_num_rows($z); // Gives zero
if ($num > 0) {
while ($row2 = mysqli_fetch_array($z)) {
$no = $row2['orders'];
$id = $res . $no;
}
}
else {
echo "none selected";
}
As discussed in the comment. By printing the query var_dump($query), you will get the exact syntax that you are sending to your database to query.
Debugging Tip: You can also test by pasting the var_dump($query) value in your database and you will see the results if your query is okay.
So update your query syntax and print the query will help you.
$query = "SELECT * FROM `seller` WHERE `restaurant` = '$res'";
var_dump($query);
Hope this will help you and for newbies in future, how to test your queries.
Suggestion: Also see how to write a mysql query syntax for better understanding php variables inside mysql query
The problem is the way you're using $res in your query. Use .$res instead. In PHP (native or framework), injecting variables into queries need a proper syntax.
$sqlorg = mysql_query("SELECT * FROM `organization`");
while($orgrows = mysql_fetch_array($sqlorg)) {
//$dborgid = $orgrows['org_id'];
$dborgnme = $orgrows['org_name'];
}
if ($dborgnme == $orgexist) {
echo "<script type='text/javascript'>
alert('Organization Name Already Used by other Organization');
history.back();
</script>";
} else {
$orginsrt = mysql_query("INSERT INTO `organization`(`org_id`,`org_name`,`org_desc`,`category`,`vision`,`mission`,`col_id`,`image`) VALUES ('$orgid','$orgexist','$orgdesc','$orgcat','$orgvis','$orgmis','$getcol','$image')");
echo "<script type='text/javascript'>
alert('Proceed to next Step');</script>";
//require ('orgsignup.php');
header ('Location:orgsignup2.php');
//echo "Not in the Record";
}
There are multiple issues with this question, and as such can't easily be answered - I'm writing this "answer" as a quick guide to Kio Rii and to get more information:
1) Don't use MySQL, use MySQLi for procedural DB/PHP interactions.
2)
while($orgrows = mysql_fetch_array($sqlorg)) {
//$dborgid = $orgrows['org_id'];
$dborgnme = $orgrows['org_name'];
}
The value $dborgnme will only ever hold the final value from all the rows fetched from the database. Consider reformatting the While statement to wrap outside the following if(){} ... else{}
3) Add some context and information to your question - what are you checking for? Where do values such as $orgexist come from? What events do you want to occur if a data exists or what happens if a data doesn't exist?
4) If you're only checking the name, you can better do it with a better SELECT statement as the current select is grabbing all the MySQL rows, so try
take :
$sqlorg = mysql_query("SELECT * FROM `organization`");
and turn it into
$sqlorg = mysql_query("SELECT * FROM `organization` WHERE org_name LIKE '%".$orgexist."%' ");
which will only return you rows if the names are very similar. You can then use the output of this (count of rows returned) to carry on the script logic.
5) Yes, my solution in part 4 is quick and dirty, and PDO or MySQLi prepared statements are much, MUCH better and more secure than old MySQL and variable injection into the SQL statement.
Additional debugging:
you would probably find this very useful:
$orginsrt = mysql_query("INSERT INTO `organization`(`org_id`,`org_name`,`org_desc`,`category`,`vision`,`mission`,`col_id`,`image`) VALUES ('$orgid','$orgexist','$orgdesc','$orgcat','$orgvis','$orgmis','$getcol','$image')") or die("insert fail: ".mysql_error());
This will tell you why an insert failed, if it did fail.
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.
Editing someone else's code here, so I can't change the field in the database called title or change to MySQLi etc :/
The code connects to the DB without problems, but always pulls in zero results.
$strSQL = "SELECT * FROM newproducts WHERE 'title' LIKE ('%$q%')";
$sql = mysql_query($strSQL) or die(mysql_error());
$num_rows = mysql_num_rows($sql);
if ( $q == '' ) {
echo '<p class="black-text">Please provide a search term.</p>';
}
else if ( $num_rows <= 0 ) {
echo '<p class="black-text">Your search for <b>'.$q.'</b> returned <b>0</b> results.</p>';
}
else {
echo '<p class="black-text">Your search for <b>'.$q.'</b> returned <b>'.$num_rows.'</b> result(s).<br/><br/>';
while($row = mysql_fetch_assoc($sql)) {
echo '- '.$row['title'].' [Read more]<br/>';
}
echo '</p>';
}
Could it be a case issue? I've tried searching for lower and upper strings, but still zero results.
In MySQL single quotes denote strings:
SELECT * FROM newproducts WHERE 'title' LIKE ('%$q%')
Should be
SELECT * FROM newproducts WHERE title LIKE ('%$q%')
Additionally, you are testing for if ($q == '') after you have performed the query - you may want to do that before - but that isn't causing your issue.
And lastly, you are at risk of SQL injection by using potentially unsafe user input - but I'm not going to delve into that as it isn't directly related to your question. Most PHP developers are using prepared statements these days to make their queries safer (and because the old style of running queries is going to be deprecated).
Why won't this query work?!?
Error
Parse error: syntax error, unexpected T_STRING in E:\xampp\htdocs\pf\shop\buy.php on line 5
Example Info For Variables
$character->islots = 20
$chatacter->name = [RE] Tizzle
$e2 = 10
The Function
function increaseSlots($e2) {
$slots = ($character->islots)+($e2);
mysql_query('UPDATE `phaos_characters` SET `inventory_slots`="'.$slots.'" WHERE `name`="'.$character->name.'"'); // <-- Line 5
if (mysql_affected_rows() != 0) {
echo 'Inventory Size Incresed By '.$e2.' Slots';
}else{
echo mysql_error();
}
}
Look at the docs: http://php.net/manual/en/function.mysql-num-rows.php
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set. To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
You need to use mysql_affected_rows() or better yet, PDO or mysqli.
$slots = ($character->islots)+($e2);
Looks like there is a typo. Try:
$slots = ($character->slots)+($e2);
First off you should know that mysql_num_rows only returns a valid result for SELECT or SHOW statements, as stated in the PHP documentation. You can use mysql_affected_rows() for your particular needs.
However, the old PHP MySQL API (that you are using) is being phased out, so I would recommend using mysqli or PDO for your DB connection needs.
While keeping with your requirements, though, you can try to use the following syntax to make sure you receive the MySQL error if it throws one. Your PHP script will stop, but you will see the error.
$query = sprintf('UPDATE `phaos_characters` SET `inventory_slots`=%d WHERE `name`="%s"',$slots,$character->name)
$result = mysql_query($query) or die(mysql_error());
As a final idea, in situations like this it helps to print out your resulting $query and run it manually through something like phpMyAdmin to see what happens.
Bleh... I Found a better way to do it for the time being.. sorry to waste your guys' time...
I just threw the $character object into a variable before processing the function.
function increaseSlots($e2,$charname,$charslots) {
$slots = $charslots+$e2;
mysql_query('UPDATE `phaos_characters` SET `inventory_slots`="'.$slots.'" WHERE `name`="'.$charname.'"');
if (mysql_affected_rows() != 0) {
echo 'Inventory Size Incresed By '.$e2.' Slots';
}
}