check if any is 0 - php

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()

Related

Which is the Fastest method to check Rows existence while fetching?

From the following Queries, Which one is the most optimal and fastest to use?
[COUNT(id)]
$SQL = "SELECT name, COUNT(id) as Count FROM names WHERE name = :name";
$row = $stmt->fetch();
if ($data['count'] > 0) {
while ($row) {
$name = $row['name'];
}
} else {
return;
}
OR [rowCount()]
$SQL = "SELECT name FROM names WHERE name = :name";
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch()) {
$name = $row['name'];
}
} else {
return;
}
OR [EXISTS]
$SQLEX = "SELECT EXISTS (SELECT name FROM names WHERE name = :name LIMIT 1)";
if ($stmt->fetchColumn == 1) {
$SQL = "SELECT name FROM names WHERE name = :name";
while (row = $stmt->fetch()){
$name = $row['name'];
}
} else {
return;
}
OR [RAW]
$SQL = "SELECT name FROM names WHERE name = :name";
$row = $stmt->fetch();
if ($row) {
while($row) {
$name = $row['name'];
}
} else {
return;
}
Also i wanted to know, Why does using $stmt->fetch() with $stmt->rowCount() allows me to fetch data, But using it with $stmt->fetchColumn doesn't?
First, if you have an index on names(name), then all should be quite comparable in speed.
Second, it is always worth trying such performance tests on your own system.
Third, if names are declared as unique (or primary key) in the names table, then all should be quite fast.
In general, though, the fastest way to determine if a row is available is:
SELECT EXISTS (SELECT name FROM names WHERE name = :name)
The LIMIT 1 in the subquery is unnecessary -- EXISTS stops at the first row (whether the database uses an index or a table scan).
In general, the first method using an aggregation is the worst solution. Without an index, it is going to result in a full table scan that reads the entire table. The second might or might not read the entire table, depending on whether the database starts returning matching rows as they are available. It also has the downside of returning more data.
Ok, it seems this question needs more than one answer...
f you need to check the existence only,
if there is an unique index for the field, all methods are equal, but some of them just make no sense.
if there is no unique index, then go for EXISTS
If you need to fetch the actual data and see if there was anything returned, then just select your data and fetch it:
if only one column from a single row is expected, then use fetchColumn()
if only one row is expected, then use fetch()
if multiple rows are expected, then use fetchAll()
and then use the resulting value to see whether your query returned any data.
So if you finally made your mind as to what you're asking about, here is the most optimal code for you:
$SQL = "SELECT name FROM names WHERE name = :name";
$data = $stmt->fetchAll(PDO::FETCH_COLUMN);
if (!$data) {
return;
}
foreach ($data as $name) ...
And there is nothing wrong with fetchColumn() other than your idea to use it.

How to update specific records in database using PHP?

I have one drop down and lists are aMan, bMan, cMan.I am selecting any one of them from drop down. So whatever I am selecting from drop down I want to update that records according to list. Below update query is updating all my records because i added '$action_points' for each.
For example. If I selected bMan from the drop down then in update table will update only bMan records according to user_id.If I select aMan then update table it will update only aMan with 10.It will not effect on other.
I am getting the issue on update query.Would you help me with update query?
$result = $conn->query($sql_user);
if (isset($result->num_rows) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$action_type=$row['action_type'];// Value will be aMan,bMan, cMan
$action_points=$row['action_points']; //10, 20, 30
}
}
$sql = "UPDATE man SET aMan='$action_points',bMan='$action_points', cMan='$action_points' where user_id='$user_id'";
$result = $conn->query($sql);
Update table
You are selecting from select drop down it means it will pass the value, that you have either aMan, bMan or cMan.
so you can do it like this,
$action_type = $_GET['action_type'];
$sql = "update man set `$action_type` = '$action_value' where id = $user_id";
Above is an example.
Firstly, you should replace if (isset($result -> num_rows) >0 ) with if(isset($result)) && ($result->num_rows>0)) .The first condition returns the number of rows (which at the least is 0) and then checks if it is set. Thus, isset will always return true, even when $result is not set. The second condition solves this problem
You have the type of list to update, why don't you use it?
For eg:
$result = $conn->query($sql_user);
if(isset($result)) && ($result->num_rows>0)) {
// output data of each row
while($row = $result->fetch_assoc()) {
$action_type=$row['action_type'];// Value will be aMan,bMan, cMan
$action_points=$row['action_points']; //10, 20, 30
}
}
$sql = "UPDATE man SET $action_type = $action_points WHERE user_id='$user_id'";
$result = $conn->query($sql);
This shall automatically update the required column
U should use AND in your query
UPDATE man SET aMan='$action_points' AND bMan='$action_points' AND cMan='$action_points' where user_id='$user_id'"
Or use several update query it means once update aMan row then a query for bMan row and so on.
The issue is because you are updating the three column at a time, you have to make it conditional like:
$action_type=$row['action_type'];// Value will be aMan,bMan, cMan
$action_points=$row['action_points']; //10, 20, 30
$column = '';
if($action_type == 'aMan'){
$column = 'aMan';
}
else if($action_type == 'bMan'){
$column = 'bMan';
}
else if($action_type == 'cMan'){
$column = 'cMan';
}
$sql = "UPDATE man SET ".$column." = '".$action_points."' where user_id='$user_id'";

getting 'array' or 'Resource id #5'

So, I want to get a column to a variable.
I tried 2 methodes
mysql_query
and
mysql_fetch_array
At mysql_query I get Resource id #5.
And
At mysql_fetch_array I get array.Does some one knows how to fix this?
$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
Suppose you have column with name as 'firstname'. Then you can go with this
$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
$firstname = $userRow[0]['firstname'];
echo $firstname;
If you get multiple rows in result, you can get all rows by loop.
My understanding is that you want to call the column name from a table where the value of that column is equal to a variable? If so...
The easiest way I can think of to resolve this would be to so a search through all the tables for the value you look for based on columns and return the value. This function should help accomplish this task:
function columnToVariable($conn, $table, $variable){//SET PARAMETERS (CONNECTION STRING, TABLE NAME, VARIABLE SEARCH)
$sql = "SHOW COLUMNS FROM ".mysqli_real_escape_string($conn, $table).";"; // SQL STATEMENT
$result = $conn->query($sql); // RESULTS OF ALL ROWS
$field = array(); // ARRAY WITH COLUMNS
if($result->num_rows > 0){ // CHECK IF RESULTS FOUND
while($row = $result->fetch_assoc()){ // SET RESULTS TO ARRAY
array_push($field, $row['Field']); // APPEND ARRAY WITH FIELD NAME
}
}
foreach($field as $return){ // ITERATE THROUGH FIELD NAMES
$sql = "SELECT * FROM ".mysqli_real_escape_string($conn, $table)." WHERE ".mysqli_real_escape_string($conn, $return)." = '".mysqli_real_escape_string($conn, $variable)."';"; // SQL STRING
$result = $conn->query($sql); // QUERY RESULTS
if($result->num_rows > 0){ // IF FOUND, RETURN VALUE
return $return; // RETURN VALUE
}
}
}

Check MYSQL to see if a entry already exists without if else

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)

How can I query the mysql database for a variable, if exists create another variable, if not insert?

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

Categories