PHP - check if database column is empty - php

How do I check if a database column is empty?
I tried the following:
$check = "SELECT Name FROM data";
$name = mysqli_query($con, $check);
if(is_null($name) == true){
//run this code
}
My method was to select the column "Name" and then checking if the column is return NULL or not. For some reason, the if statement runs when I put "is_null($name) == false" but my database definitely has no data in it so surely it should return true since it should be NULL. What am I doing wrong here?
How can I check if the column of a database is empty using if statement?
Thanks.

you're treating the result as just the column.. it'd look more like
$check = "SELECT Name FROM data";
$result = mysqli_query($con, $check);
$row = mysqli_fetch_assoc($result)
if($row && $row["Name"] == null){
//run this code
}

You will need to use empty() function. change is_null to empty like this:
$check = "SELECT Name FROM data";
$name = mysqli_query($con, $check);
if(empty($name['Name'])){
//run this code
}

$check = "SELECT Name FROM data";
$name = mysqli_query($con, $check);
$nameAssoc = mysqli_fetch_assoc($name);
if(empty($NameAssoc['Name'])){
//run this code
}

You can modify your mysql query , check if any column is empty or not.
$check = "SELECT count(*) FROM data where Name is not null and Name != '' ";
$name = mysqli_query($con, $check);
if($name > 0 ){
//it means Name column is not null
}else{
// Name column is null
}

Related

How to get SELECT EXISTS() query value

I have this php code:
$query = $database->query("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID')";
if($query == 0){
echo "not registered";
}elseif($query == 1){
echo "registered"
}
If I'm not wrong, the query is suppose to return 0 or 1 and it works in my SQLite manager. What is the correct way on getting that value in Php and use it in IF ELSE statement?
If you only need a single value, you can use querySingle:
$result = $database->querySingle("SELECT EXISTS(SELECT * FROM contacts WHERE contact_id = '$contactID'");
Otherwise, with normal queries, the result returned by ->query isn't actually the data itself, but an identifier you would use to get data from the database:
$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}

run insert query after select query mysql in php

i am trying to insert into multi table after select query return 0 (not found raws) select query working and insert query never done when submite "displayid" and there is no any syntax error
code:
<?php
if ($_POST["displayid"] == TRUE) {
$sqlid = "SELECT * FROM doc1 WHERE idnum ='$pidnum' AND stats='$ok'";
$result = mysqli_query($conn, $sqlid);
if (mysqli_num_rows($result) > 0) {
$sqlup = "UPDATE doc1 SET m_phone='$pm_phone', seen='$dataseen' WHERE idnum ='$pidnum'";
mysqli_query($conn, $sqlup);
$found = 1;
} else {
$found = 0;
$sqlfail = "INSERT INTO fail(fname,lname,tname,funame,idnum,m_phone,reg_date)
VALUES ('$pfname','$plname','$ptname','$pfuname','$pidnum','$pm_phone','$todaydate')";
$conn->query($sqlfail)
}
}
?>
Use this code:
$sqlfail = "INSERT INTO fail(fname,lname,tname,funame,idnum,m_phone,reg_date)
VALUES ('".$pfname."','".$plname."','".$ptname."','".$pfuname."','".$pidnum."','".$pm_phone."','".$todaydate."')";
make similar changes for update command as well
you actually have one error
$conn->query($sqlfail)
should be
$conn->query($sqlfail);
AND stats='$ok'";
i can't see a variable with this name i think you mean AND stats='ok'";

Check if a PHP variable exists in a MySQL table

I'm trying to check if the content of the variable $host exists in the ID column of my database. Afterwards I want it to assign the corresponding value to $exists, if the entry is in the database or not.
For some reason this part of my script is always returning the same result, regardless if $host is contained in the database or not. Please help :)
$query = mysqli_query($conn, "SELECT 'ID' FROM 'servers' WHERE 'ID' = '$host'");
if (empty($query)) {
$exists = "false";
}
else {
$exists = "true";
}
This line
$query = mysqli_query($conn, "SELECT 'ID' FROM 'servers' WHERE 'ID' = '$host'");
needs to be like this:
$query = mysqli_query($conn, "SELECT `ID` FROM `servers` WHERE `ID` = '$host'");
Right now, you are selecting ID as a string, so you need to put table and column names in `` and you put strings (or variables containing strings in ' ' )
and then do
$count = $conn -> num_rows($query);
if ($count < 1 ) {
$exists = "false";
}
else
{
$exists = "true";
}
to actually check the number of rows containing $host 's value
Also, you should at least use
$host = mysqli_real_escape_string($conn, $host);
before using a variable in a query to avoid mysql injection, but better use prepared statements. There are some links in the comments to your question which will help you with that.
Sidenote:
Having used or die(mysqli_error($conn)) to mysqli_query() would have signaled the error.
$query = mysqli_query($conn, "SELECT ID FROM servers WHERE ID = '".$host."'");
if (empty($query)) {
$exists = "false";
}
else {
$exists = "true";
}

PHP How to check if a string already exists in a MySQL table

I'm having a user enter a desired name, then check the database to see if it exists before I make it. It's not working properly though, sometimes it echos the right thing, sometimes not.
$makeName = $_POST["userName"];
$nameFind = "SELECT userName FROM usertable WHERE userName = $makeName";
$nameCompare = mysqli_query($con, $nameFind);
if($nameCompare == false)
{
echo "This is a new name";
}
else
{
echo "Pick a new name please";
}
The query doesn't fail just because it returns no rows. Use mysqli_num_rows() to find out if there was a match or not.
Also xkcd
Don't do it that way.
Instead,
Create a unique constraint on the column "username".
Insert the user's desired name.
Trap the error when the desired name already exists.
Why? Your approach always requires two round-trips to the database, and it doesn't account for errors. And you have to trap errors anyway; there are lots of things that can go wrong with an insert statement.
Use quotes and escaping:
"select userName FROM usertable WHERE userName = '" . mysqli_real_escape_string($makeName) . "'"
And then use mysqli_num_rows()
$result = mysqli_query($query); $num_rows = mysqli_num_rows($result);
if(mysqli_num_rows($nameCompare))
{
echo "Pick a new name please";
}
else
{
echo "This is a new name";
}
this will check the result, if there is a row, it's already used.
You need two queries for that anyways
$username = mysqli_real_escape_string($con,$username);
$query = "SELECT * FROM tbl_login WHERE username='$username'";
$result = mysqli_query($con,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 ) {
echo 'false';
}
else{
$query_insert = "INSERT INTO login (username, password)VALUES ('$username','$password');";
$result = mysqli_query($con,$query_insert) or die(mysqli_error());
}

update and insert mysqli table

I'm trying to check if the leaguename name already exists if it does then check if it is higher than the existing score. if its higher then replace the quizscore else insert the leaguename and quizscore into the table league_quiz.
The code seem to insert the values in my table, but it do not seem update if the name is equal to previous and the score is higher?
I get this error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, string given in
My code:
<?php
$name = (string)$_POST['name'];
$score = (string) $_POST['score'];
$link = mysqli_connect("mysql12.gigahost.dk","username","password","dirts_mysql");
$query = "SELECT leaguename, quizscore FROM league_quiz WHERE leaguename = '$name' AND quizscore < '$score'";
if(mysqli_num_rows($query)) {
mysqli_query($link,"UPDATE league_quiz SET quizscore = '$score'");
} else {
mysqli_query($link,"INSERT INTO league_quiz (leaguename, quizscore) VALUES ('$name', '$score')") or die(mysqli_error($link));
}
?>
mysqli_num_rows expects the result of a query and not the string of the query itself.
Firstly you must execute your query :
$result = mysqli_query($link,$query);
and then you can count the number of rows
$numRows = mysqli_num_rows($result);
Between those two:
$query = "SELECT leaguename, quizscore FROM league_quiz WHERE leaguename = '$name' AND quizscore < '$score'";
if(mysqli_num_rows($query)) {
Have you tried to write this code?
$result = mysqli_query($query);
and then use mysqli_num_rows on the result of the query?
Try the followowing:
$result = mysqli_query($query);
if (mysqli_num_rows($result)) {
...

Categories