MySQL: Num Rows not working - php

I've stumbled upon a simple MySQL error, and it seems my attempts of fixing it are effortless. The problem, it's not counting.
Before I go further, I know that mysql_* is Deprecated, and that I shouldn't use it. I should use mysqli_* or PDO.
This is my Query, and yes, the echo is just for testing.
$ms_sql = mysql_query("SELECT * FROM mijnsp WHERE sp_username = '".$user['username']."'");
while ($mijnspusers = mysql_fetch_assoc($ms_sql)) {
$ms_count = mysql_num_rows($ms_sql);
if($ms_count <= 0){
echo "Result is empty";
}else{
echo $mijnspusers['new_username'];
}
I've tried to change the IF, but with no effect;
if($ms_count <= "0"){
or, like this
if($ms_count <= '0'){
Thank you in advance,
Pascal

Call
$ms_count = mysql_num_rows($ms_sql);
before the while() loop.

You should do the mysql_num_rows() before going into the loop. If the num is 0, then you'll never run the loop to begin with.
Your code should be:
$ms_sql = mysql_query("SELECT * FROM mijnsp WHERE sp_username = '".$user['username']."'");
$ms_count = mysql_num_rows($ms_sql);
if($ms_count == 0){
echo "Result is empty";
}else{
while ($mijnspusers = mysql_fetch_assoc($ms_sql)) {
echo $mijnspusers['new_username'];
}
}`

Related

Give another random int if number exists in database (PHP)

I am trying to make a script to check if an int is already added to my database. If so, it will re-generate another random number and check again. If it doesn't exist, it'll insert into the database.
However, I am having troubles. If a number exists, it just prints out num exists, how would I re-loop it to check for another and then insert that? I have tried to use continue;, return true; and so on... Anyway, here is my code; hopefully someone can help me!
<?php
require_once("./inc/config.php");
$mynum = 1; // Note I am purposely setting this to one, so it will always turn true so the do {} while will be initiated.
echo "attempts: ---- ";
$check = $db->query("SELECT * FROM test WHERE num = $mynum")or die($db->error);
if($check->num_rows >= 1) {
do {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')")or die($db->error);
echo "$newnum - CAN INSERT#!#!#";
break;
}
} while(0);
}
?>
I think the logic you're looking for is basically this:
do {
$i = get_random_int();
} while(int_exists($i));
insert_into_db($i);
(It often helps to come up with some functions names to simplify things and understand what's really going on.)
Now just replace the pseudo functions with your code:
do {
$i = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $i")or die($db->error);
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
$db->query("INSERT test (num) VALUES ('$i')") or die($db->error);
Of course, you can do a little more tweaking, by shortening...
// ...
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
...to:
// ...
$int_exists = $newcheck->num_rows >= 1;
} while($int_exists);
(The result of the >= comparison is boolean, and as you can see, you can assign this value to a variable, too, which saves you 4 lines of code.)
Also, if you want to get further ahead, try to replace your database calls with actual, meaningful functions as I did in my first example.
This way, your code will become more readable, compact and reusable. And most important of all, this way you learn more about programming.
The logic is incorrect here. Your do-while loop will get executed only once (as it's an exit-controlled loop) and will stop on the next iteration as the while(0) condition is FALSE.
Try the following instead:
while($check->num_rows >= 1) {
$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if ($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')") or die($db->error);
echo "$newnum - CAN ISNERT#!#!#";
break;
}
}
Sidenote: As it currently stands, your query is vulnerable to SQL injection and could produce unexpected results. You should always escape user inputs. Have a look at this StackOverflow thread to learn how to prevent SQL injection.
Here is an example of some code that I threw together using some of my previously made scripts. You will notice a few changes compared to your code, but the concept should work just the same. Hope it helps.
In my example I would be pulling the database HOST,USER,PASSWORD and NAME from my included config file
require_once("./inc/config.php");
echo "attempts: ---- ";
$running = true;
while($running == true) {
//create random number from 1-5
$newnum = rand(1,5);
//connect to database
$mysqli = new mysqli(HOST, USER, PASSWORD, NAME);
//define our query
$sql = "SELECT * FROM `test` WHERE `num` = '".$$newnum."'";
//run our query
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//check results, if num_rows >= our number exists
if (mysqli_num_rows($check_res) >= 1){
echo $newnum . " exists! \n";
}
else { //our number does not yet exists in database
$sql = "INSERT INTO `test`(`num`) VALUES ('".$newnum."')";
$check_res = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
if ($check_res){
echo $newnum . " - CAN ISNERT#!#!#";
// close connection to datbase
mysqli_close($mysqli);
}
else{
echo "failed to enter into database";
// close connection to database
mysqli_close($mysqli);
}
break;
}
}
I would also like to note that this will continue to run if all the numbers have been used, you may want to put in something to track when all numbers have been used, and cause a break to jump out of the loop.
Hope this helps!

Show different image depending on value in variable

just want to make sure I'm going in the right direction with this. I have an image which I want to be replaced/changed if the value of a variable is either 0/1. So here is the code from the guy doing the server side stuff.
<?php
//Requires mysql_connect to create the connection
$link_state = 0;
//If you so wish you don't have to check for a connection, but may be a good idea leave this in.
if ($mysql_connection['connected'] == true) {
$result = mysql_query("SELECT * FROM link");
//The bit we are looking for should be the first row, and we should only get one row
$count = mysql_num_rows($result);
if ($count <= 0) {
//Interesting...
$mysql_error['error'] = true;
$mysql_error['description'] = "ERROR: No rows were returned from table 'link'";
} else {
//We should be ok to continue
if ($count > 1) {
$mysql_error['error'] = true;
$mysql_error['description'] = "WARNING: Found more than one row in 'link' table!";
}
$row = mysql_fetch_array($result);
$link_state = intval($row['state']);
}
} else {
$mysql_error['error'] = true;
$mysql_error['description'] = "ERROR: No mysql connection!";
}
/*
After the completion of this page, $link_state will be one of two things:
* 0 = offline
* 1 = online
Throws to $mysql_error:
1 Warning
2 Errors
*/
?>
Okay, so I'm assuming by that little bit of code I will then have a value of either 0 or 1 in $link_state.
So from this can I then just do a simple inline script like this to get my relevant image?
<img src="img/<?=($link_state=="0"?"off.jpg":($link_state=="1"?"on.jpg":))?>" />
Any insight would be great :)
Thanks in advance.
try this
<?php $img = ($link_state == "0") ? "off.jpg" : "on.jpg"; ?>
<img src="./img/<?php echo $img; ?>" />
also use mysqli_* since mysql_* is depreciated.

as of now it just ignores the if statement and gives them a ticket everytime.php, mysql, If else

Alright so i'm trying to put value in an array and shuffle them to be random, then have it use that random value in a query. I know my code is bad and not to use mysql anymore lets stay off that topic please.
I don't understand why this isn't working I have other things like it that work just fine.
right now it ignores the if statement and gives them a ticket each time.
if(isset($_POST['Submit'])) {
$ticket = array("0","0","0","0","0","0","0","1");
shuffle($ticket);
if ($ticket >= 1) {
echo "You have Found a Shop Ticket!" ;
mysql_query("UPDATE users SET ticket=ticket+1 WHERE username = '".$_SESSION['username']."'")
or die(mysql_error());
} else {
echo "";
}
}
You're checking if the entire array is >= 1, which is obviously TRUE all the time.
Pick a value instead:
$ticket = array_shift($ticket); // do this after you shuffle
try
if (current(shuffle($ticket)) >= 1) {
# yay
} else {
# ney
}
$ticket is an array, not a number.
u could use foreach or array_map to do this.
example:
function foo($n){
if($n >= 1){//do something}
}
$ticket = array("0","0","0","0","0","0","0","1");
shuffle($ticket);
array_map('foo', $ticket);

goto equivalent for php version < 5.3.0?

I need to use the goto operator in my code as I can't seem to think of a way around it. However the problem is my host only has PHP version 5.2.17 installed.
Any ideas?
Below is my code:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
goto skip;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
skip:
There are a few anti-patterns in your code. Let's clean it up. I'll explain what's been changed in a jiffy.
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
}
}
First things first: There is no need to perform a query, fetch all of the results, then loop through those results (in_array) looking for a specific value. Let the database do that for you by expressly looking only for rows where inserted is the string literal "n".
Because we know that we're only getting "n" records back, we just need to check if there are any results. If so, run the query. If there are no "n" records, the UPDATE isn't run.
If you need to know that the UPDATE ran, add a check for it:
$ran_update = false;
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
$ran_update = true;
}
}
if($ran_update) {
// ...
}
You want to use the correct control word to break from the loop:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
break;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
The break keyword will do exactly what you want: End the execution of the while loop. Never ever ever use a goto!
As a direct response to the title of this post:
do{
if (!$condition){
break;
}
// Code called if conditions above are met
}while(0);
//Code always called
In some circumstances, this, or a goto, can make for very tidy and readable code.
First, you could use a break to exit your initial loop. Second, if you need to test for anything, set a variable (must be global not local) as a flag or indicator before calling break, then do a conditional test statement where your skip line is to perform any additional steps you need.

how to echo the line one time under the while loop

I have a code like this
<?php
$getLeftSide = 'select * from leftmenu';
$result = $db -> query ($getLeftSide) or die ("$db->error");
if ($result) {
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
echo "<div class='left_main_cat'>Web and Desigen</div>";
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
}
?>
I need to echo this line one time
echo "<div class='left_main_cat'>Web and Design</div>";
of course it's under the while loop so it print it self many times
is there is a why to solve this and print this line one time only.
As Ben suggests, the easiest and clearest solution is to use a boolean check variable:
$catFound = FALSE;
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
// We only want this category printed for the first category,
// if it exists.
if(!$catFound) {
echo "<div class='left_main_cat'>Web and Desigen</div>";
$catFound = TRUE;
}
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
Although it seems better to use a boolean variable and a comment to make clear your intent.
Ugly, but I'm not that good at PHP yet!
$has_printed = FALSE;
while ($row = $result -> fetch_object()) {
$getCat = $row -> left_item_cat;
if ($getCat == 1) {
if(!$has_printed){
echo "<div class='left_main_cat'>Web and Desigen</div>";
$has_printed = TRUE;
}
echo "<a href='index.php?learn_id= $row->left_item_link'><div class='left_label_sub'>$row->left_item_name</div></a>";
}
}
Simple solution: Add another boolean variable with default value false Then just check if false, print your text and set it true.
adding a boolean or check variable or any kind of conditional inside of a loop is a very bad idea imho, i NEVER do it. every time you swing through the loop, the condition has to be checked. it's like a badly written switch/case.
figure out a way to do it before the loop.
unroll the loops, most people do it to save space but most compilers will unroll them anyway for optimization
stick it before the loop
find a java or css way to hide it until the loop is done or you want to display stuff.

Categories