Hi I have a long page of code with multiple if else statemets, what i would like to do is check a database to see if that Ip address is already in the table
currently i am doing it like this
$result = mysql_query("SELECT * FROM masterip_details WHERE ip_address='$ip_address' AND client_id='$client_id'") or die(mysql_error());
$num_rows = mysql_num_rows($result);
//IF THE RESULT IS MORE THAN 0, THIS MEANS THAT THEY ARE A RETURNING VISITOR
if( $num_rows > 0 ) {
/// Add returning Script here
} else {
//Add code
}
Is there a way i could do this with out the if else statement?, so for example if the record was in the database just return a value of 1.
Thanks, any suggestions would be appreciated.
You can use count to get the number of rows with that value.
$result = mysql_query("SELECT count(*) FROM masterip_details WHERE ip_address='$ip_address' AND client_id='$client_id'") or die(mysql_error());
return $result > 0; //returns a boolean
This way you will get a 0 if the value doesn't exist on the database and a number higher than 0 if it does.
Make use of SELECT IF EXISTS on MySQL.
SELECT IF( EXISTS(
SELECT *
FROM masterip_details
WHERE `ip_address`=? AND `client_id`=?), 1, 0)
Related
I am looking for a way to count the number of times a result occurred for team X and a number of times a result occurred for team Y.
Example
I have a table containing a sports competition results from 2009 - present.
A user can query the DB to retrieve all results when selected 2 teams played against each other.
The results gets displayed in tables as follows:
Now I am looking for a way to calculate the total number of games played between the two selected teams, and how many time the result went in favour of (in this example) Stormers, and how many times the result went to the Sharks
Is it possible to do this without changing data in my table table? Ive been trying to come up with some sort of logic to solve the above problem but I am stumped.
My code to retrieve data follows:
if($venue == "hometeam"){
$result= " SELECT *
FROM `results`
WHERE `hometeam` = '$team1' && `awayteam` = '$team2'" or die(mysql_error());
}
else if($venue == "awayteam"){
$result = " SELECT *
FROM `results`
WHERE `awayteam` = '$team1' && `hometeam` = '$team2'"or die(mysql_error());
}
else if($venue =="all"){
$result = " SELECT *
FROM `results`
WHERE (`hometeam` = '$team1' AND `awayteam` = '$team1') OR (`hometeam` = '$team2' AND `awayteam` = '$team2')"or die(mysql_error());
}
My code to display the data:
cho '<td>'.$row['gamedate'].'</td>';
echo '<td>'.$row['hometeam'].'</td>';
echo'<td>'.$row['awayteam'].'</td>';
echo'<td>'.$row['homescore'].'</td>';
echo'<td>'.$row['awayscore'].'</td>';
if($row['homescore'] > $row['awayscore']){
echo'<td style="background-color:yellow">'.$row['hometeam'].'</td>';
}
else echo'<td>'.$row['awayteam'].'</td>';
Any help or advice will be greatly appreciated. Thanks in advance
$rs = mysqli_query($link, "select * from results where result = \"Stormers\"");
$stormers = mysqli_num_rows($rs);
$rs = mysqli_query($link, "select * from results where result = \"Sharks\"");
$sharks = mysqli_num_rows($rs);
Now, variable $stormers will show the number of results matching Stormers, and Sharks will match results with Sharks. You can also use the Count() MySQL function instead of select, but I was assuming you might want to get more data from it instead of just a number later on.
How about
SELECT `result`, COUNT(*) FROM `results` WHERE `hometeam` IN (`$team1`,`$team2`) AND `awayteam` IN (`$team1`,`$team2`) GROUP BY `result`
I'm assuming you're iterating through the results to gen the table rows. Why not just count the wins up while you do that?
$homeTeamWins = 0;
$awayTeamWins = 0;
$ties = 0;
while( $row = $result->fetch_object() ) {
if( $row->homescore > $row->awayscore ) {
$homeTeamWins++;
} elseif( $row->homescore < $row->awayscore ) {
$awayTeamWins++;
} else {
$ties++;
}
// output the html rows
}
I have the code below and I just want to count from the table members how many people have a 1 in the column loggedin and echo that back. I'm sure I'm missing something small, I just can't see it.
<?php
include ('functions.php');
connect();
$result = mysql_query("SELECT * FROM members WHERE loggedin = '1'");
$num_rows = mysql_num_rows($result);
$total_mem = $num_rows + (1223);
return $total_mem;
echo $total_mem;
?>
The echo will never be called because it is after the return statement.
Remove the return statement and the value should be shown.
Why not let your database do the counting for you?
$result = mysql_query("SELECT count('id') as logged_in_count FROM members WHERE loggedin = '1'");
$row = mysql_fetch_assoc($result);
$num_rows = $row['logged_in_count'];
$total_mem = $num_rows + (1223);
echo $total_mem;
return $total_mem;
You're never going to hit that echo statement, because you have a return statement right above it.
Why not use SELECT COUNT(1) FROM members WHERE loggedin = 1, and then pull the value directly from that? You'll save time because it will only need to return 1 row instead of all the rows, when all you want is the count.
I have this code:
$local_id = $_GET['id'];
$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." LIMIT 0, 1");
while($row = mysql_fetch_array($sql)){
$video_id = $row["youtube_id"];
// the rest
}
how can i check if $local_id does not exist in the db and display an error?
mysql_num_rows
if(mysql_num_rows($sql) == 0) {
//Show error
}
$sql = dbquery("select count(*) from videos where id = ".$local_id." LIMIT 0, 1");
$row = mysql_fetch_row($sql);
if($row[0] == 0)
echo 'error';
You can use the following query:
"SELECT COUNT(*) FROM `videos` WHERE `id` = ".mysql_real_escape_string($local_id)
This query will return one number: how many records have matched your query. If this is zero, you surely know that there are no records with this ID.
This is more optimal than other solutions posted in case you only want to check for the existence of the ID, and don't need the data (if you use SELECT * ..., all the data will be unnecessarily sent from MySQL to you). Otherwise mysql_num_rows() is the best choice, as #Ryan Doherty correctly posted.
Be sure to ALWAYS escape data that came from the outside (this time GET) before you put it into a query (mysql_real_escape_string() for MySQL).
If you fail to do so, you are a possible victim for SQL Injection.
You could have a $count variable and increment it in the while loop. After the loop, check the count, if it is 0, then echo an error message.
say I have a variable
$id = mt_rand();
how can I query the mysql database to see if the variable exists in the row id, if it does exist then change the variable $id, once the variable is unique to all other stored ids, then insert it into the database?
Thanks you guys.
$con = mysql_connect("<host>","<login>","<pass>");
if ($con) {
mysql_select_db('<schemata>', $con);
$found = false;
while (!$found) {
$idIamSearching = mt_rand();
$query = mysql_query("SELECT count(*) FROM <table> WHERE <idColumnName>='".$idIamSearching."'");
$result = mysql_fetch_row($query);
if ($result[0] > 0) {
mysql_query("INSERT INTO <table> (<column>) VALUES ('".$idIamSearching."')");
$found = true;
}
}
mysql_close($con);
}
Your description is hard to understand, so, this is something that could give you pointers...
'SELECT COUNT(*) as count from table where row_id="'.$variable.'" LIMIT 1'
make sure to escape the variable if it's user input or if it's going to have more than alphanumeric characters
then fetch the row and check if count is 1 or greater than 0
if one, then it exists and try again (in a loop)
although, auto increment on the id field would allow you to avoid this step
$bExists = 0;
while(!$bExists){
// Randomly generate id variable
$result = mysql_query("SELECT * FROM table WHERE id=$id");
if($result){
if(mysql_num_rows($result) > 0){
$bExists = 1;
} else {
// Insert into database
$bExists = 1;
}
}
1 Randomly generate id variable
2 Query database for it
2.1 Result? exit
2.2 No result? Insert
How to check with php/sql if any of fields in database that are selected in while loop is 0?
$res = mysql_query('SELECT id, name FROM table'); \\check here?
while($row = mysql_fetch_array)
{
\\or check here?
}
Thanks in advance!
EDIT:
I need to select all fields and then check if any one of them is 0.
$foundZero = false;
$res = mysql_query('SELECT id, name FROM table');
while ($row = mysql_fetch_array($res))
{
if (in_array(0, $row))
{
// This row has a zero
$foundZero = true;
}
}
if ($foundZero)
{
// at least one zero in one row has been found
}
else
{
// No zeros have been found
}
If $foundZero is true, then at least one field in one row is equal to 0. Otherwise, all fields are non-zero.
in the query add a where clause
SELECT id, name FROM table where my_field=0
then you not need to check every results, you get only the wanted results rows.
Obviously, check inside the while loop. For the query may return ZERO row.
$res = mysql_query('SELECT count(*) FROM table WHERE my_field=0'); \\check here?
if(mysql_num_rows($res) > 0)
{
while($row = mysql_fetch_array)
{
\\or check here?
}
}
If you really have to return all rows and then check for zero, add an order by clause to your query to minimize your checking.
SELECT id, name FROM table ORDER BY id DESC
then
if ($id <= 0)
handleIt()
else
proceed()