retrieve only the data from the rows those are not empty - mysql

suppose I have 2 columns username and password and I want to retrieve only the data from the rows those are not empty. how to do it in php or mysql? Plz provide solution in both php and mysql.
from the comments
I tried this SELECT * FROM users WHERE username IS NOT NULL AND username != " " and it works only for one column. What if I have to check empty fields for multiple columns?

Try this:
if((!name.eual(""))and(!password.equal("")){
// code here
}

SELECT username, password FROM table_name WHERE table_name.username!='' AND table_name.password!='';
In case you do select everything even the blank rows. with SELECT * FROM table_name
In your php assuming that $data is the output of your query do a loop like this
foreach ($arr as $key => $value){
if(($key == 'username' && $value == '') || ($key == 'password' && $value == '')){
// row with blank username and password.
}
}

$query="SELECT * FROM users WHERE username IS NOT NULL AND password IS NOT NULL"

Related

Converting empty string into null

I have a form that POST value keeps coming as "" empty string into a unique SQL field.
It has to be unique as the field is optional but jet it can not have 2 same values. The unique value does allow null multiple values.
I don't even want to say what I tried to do, I'm trying to fix this for last few days.
Closest that I got is putting '$OIB'=IF('$OIB'='',NULL,'$OIB' into NSERT INTO statement, then i get null values into a database but for some reason when the number is entered into OIB form field it puts number 1 into a database...
$result = mysqli_query($conn, "SELECT OIB, NAZIV FROM STRANKEP WHERE OIB = '$OIB' OR NAZIV = '$NAZIV'");
if(mysqli_num_rows($result) == 0) {
// row not found, do stuff...
$sql = "INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES ('$NAZIV', CASE WHEN '$OIB' = '' THEN 'NULL', '$EMAIL', '$ADRESA', '$TELEFON')";
$query = mysqli_query($conn, $sql);
This solution gets me null but not the real $OIB when entered into form, it just puts number 1.
$result = mysqli_query($conn, "SELECT OIB, NAZIV FROM STRANKEP WHERE OIB = '$OIB' OR NAZIV = '$NAZIV'");
if(mysqli_num_rows($result) == 0) {
// row not found, do stuff...
$sql = "INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES ('$NAZIV', '$OIB'=IF('$OIB'='',NULL,'$OIB'), '$EMAIL', '$ADRESA', '$TELEFON')";
$query = mysqli_query($conn, $sql);
Thank you in advance for the help.
Try
CASE '$OIB' WHEN '' THEN NULL ELSE '$OIB' END
You can use also IF Clause
Like so
INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES
('$NAZIV', IF('$OIB' = '', NULL,'$OIB'), '$EMAIL', '$ADRESA', '$TELEFON');
But as mentioned in my comment use prepared statements like in PDO https://phpdelusions.net/pdo#prepared
I would recommend nullif(). It is a built-in standard function to do exactly this:
nullif(?, '')
Note: Do not munge queries with constant values. That makes the code subject to SQL injection attacks. And it can introduce very hard-to-debug errors. Use parameters!

Query where clause based on user input

I have some html that allows the user to search with 2 criteria: name and cost. I am trying to make it so that the query displays results based on what the user enters for name and cost. There are 3 cases: name entered no cost, cost entered no name, both entered
SELECT name, cost FROM table WHERE...
I know to get the values entered by doing $_POST['name'] and $_POST['cost'] but I am struggling on how to set up the query to display the information based on the possible user input combinations
Is this what you basically want?
select . . .
from t
where (name = #name or #name is null) and
(cost = #cost or #cost is null);
Here #name and #cost are parameters used to pass the user input values into the query.
For my case, I always arrange the SQL like below:-
$nane = $_POST['name']:
$cost = $_POST['cost'];
if((isset($nane) && ($nane != "")) && (isset($cost) && ($cost != "")))
{
$sql = "select name,cost from table where columnNm ='".$nane."' and columnNm1 = ".$cost;
}
else if((isset($nane) && ($nane != "")) && (!isset($cost) && ($cost == "")))
{
$sql = "select name,cost from table where columnNm ='".$nane."'";
}
else if((!isset($nane) && ($nane == "")) && (isset($cost) && ($cost != "")))
{
$sql = "select name,cost from table where columnNm1 = ".$cost;
}
I solve my issues like this. If you think it's suitable for you then you may use it.

Symfony2 DBAL Update method returning 0

I'm getting a strange result, where an update method (http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#update) call that activates/deactivates site users accounts in my mySQL database sometimes are not updated and returns a 0. Here is the code:
$user_id = '198';
$sqlSetStmnt= [ 'activation_code' => NULL, 'active' => 0 ];
$conn = $this->get( 'database_connection' );
try {
$result = $conn->update( 'users', $sqlSetStmnt,[ 'id' => (int)$user_id ] );
}
catch( Exception $e ) {
$error = $e->getMessage();
throw new \Exception( 'update user account data function -- ' .
'error: ' . $error . ' - ' .
'unable to update your account!' );
} // End of catch( Exception ) block.
if( ( $result === FALSE ) || ( $result !== 1 ) ) {
throw new \Exception( 'update user account data function -- ' .
'update return value: ' . $result . ' - ' .
'unable to update your account!' );
} // if( ( $result === FALSE ) || ( $result !== 1 ) ) ...
The users table has an id int(11) column which is the primary key, an active tinyint(1) column, and activation_code varchar(40) NULL column.
Please note the $user_id variable contains a string value of '198', but it is cast to an int when creating the $sqlSetStmnt value.
Inspecting the users table confirms that there was a row in the users table with the id column value of 198 at the time of the update call.
The account used when running the update call has enough privileges to change the row active and activation_code column values.
There are no other users in the system or accessing the database, so there aren't any locks on the row.
I inspected the code using x-debug, and the values of the $user_id and $sqlSetStmnt variables were properly set to the values that I expected, that $result was set to 0 by the update method, and that no exceptions were thrown by the update method call.
By the way, there is no need to using variable binding because the values in the $user_id and $sqlSetStmnt variables are not input by an user, so no possibility of SQL-Injection, or Buffer-Overrun.
Is there some way to get information from DBAL about why the update method returned 0?
Thank you.
Before solving this issue I switched from:
$result = $conn->update( 'users', $sqlSetStmnt, [ 'id' => (int)$user_id ] );
to:
$sqlUpdateStmnt = 'UPDATE `users` SET field = value ' .
'WHERE `id` = ' . $user_id;
$result = $conn->executeUpdate( $sqlUpdateStmnt );
and got exactly the same result, where some updates would return 0 rows when there definitely was a row in the users table with an id matching the value of $user_id.
I got around this problem by fetching the existing row and then only updating the row when the fields in the set-clause were different than the same columns from the table.
This tells me that the 0 return value wasn't that there were no matching rows, but that the updated didn't have any effect on any rows.
So this issue isn't a bug, so much as a misunderstanding of the result. However, the problem still exists when using the update() method of how to determine when the update failed due to no matching rows and when no changes were made.
The solution that I ended up solves this at the cost of a pre-fetch to verify that the update would affect a row. In my case, with a multi-user database application, pre-fetching isn't actually a problem because the row that is to be updated could have been deleted by another user before the update tries to make its change. But, it would be nice if both update methods explained this more clearly, and returned different values: 0 for no affected rows and FALSE for no rows found.

Update MySQL data if URL accessed

I would like to know if it's possible to update a MySQL value for a logged in user if he accessed a certain URL. If possible, what's the best way to do so?
Example:
MySQL, 3 columns:
username id count
Each time the user access count.php?ref=12 the "count" value should be changed (if it was 10) to 9.
I have the found the following solution and seems to be working:
$data = mysql_query("SELECT * FROM admin where username='$user_check' ")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
$status = $_GET['urlvalue'];
if($status == "0")
{
$sql = mysql_query("UPDATE admin SET count = (count - 1) where username='$user_check'");
}

PDO UNION function only processes first SELECT statement

Okay so I have three different types of users (Developers, Designers & Employers) all of whom have different database tables. I have successfully developed a script that can log in a user from any of the three user tables using UNION. However I have now introduced email verification on sign up so I need to test whether the 'confirmed' field (in each table) has a value of '1' to process a successful login (if the value is 0, the user will not be able to log in).
public function email_confirmed($email) {
$query = $this->db->prepare("SELECT
COUNT(developers.id) FROM " . DB_NAME . ".developers WHERE developers.email= ? AND developers.confirmed = ?
UNION SELECT COUNT(designers.id) FROM " . DB_NAME . ".designers WHERE designers.email = ? AND designers.confirmed = ?
UNION SELECT COUNT(employers.id) FROM " . DB_NAME . ".employers WHERE employers.email = ? AND employers.confirmed = ?
");
$query->bindValue(1, $email);
$query->bindValue(2, 1);
$query->bindValue(3, $email);
$query->bindValue(4, 1);
$query->bindValue(5, $email);
$query->bindValue(6, 1);
try{
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1){
return true;
}else{
return false;
}
} catch(PDOException $e){
die($e->getMessage());
}
}
At the moment however (using the function below), only a developer can log in. If you attempt to log in using a designer or an employer account, the error below shows. Any ideas why this is happening?
if ($users->email_confirmed($email) === false) {
$errors[] = 'Sorry, but you need to activate your account. Please check your emails.';
} else // carry on logging in user
This is your query:
SELECT COUNT(developers.id)
FROM " . DB_NAME . ".developers
WHERE developers.email= ? AND developers.confirmed = ?
UNION
SELECT COUNT(designers.id)
FROM " . DB_NAME . ".designers
WHERE designers.email = ? AND designers.confirmed = ?
UNION
SELECT COUNT(employers.id)
FROM " . DB_NAME . ".employers
WHERE employers.email = ? AND employers.confirmed = ?
It is fetching three rows, then removing duplicates, and ordering them arbitrarily. You are then reading the value (the count) from one of these rows.
Taking the approach you are taking, I think you want:
select COUNT(*)
from ((select 1
from " . DB_NAME . ".developers
where developers.email= ? AND developers.confirmed = ?
) union all
(select 1
from " . DB_NAME . ".designers
where designers.email = ? AND designers.confirmed = ?
) union all
(select 1
from " . DB_NAME . ".employers
where employers.email = ? AND employers.confirmed = ?
)
) t