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";
}
Related
I am trying to create a page where I can get the record values of a Database. My query is like this:
So I need to get the number of the values 1 on status (as count) from the tableexample if they exist and count them, if they do not exist, I need to get the value as 0 from it. To get the values I use this code and it works great, but I cannot seem to have the value return 0 on my PHP code if no results are found. I am a bit lost.
$user = $_SESSION["user"];
$systems = mysqli_connect("localhost", "root", "", "testdatabase");
$query = "SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'";
$request = mysqli_query($systems, $query);
if (mysqli_num_rows($request) > 0) {
while ($row = mysqli_fetch_array($request)) {
echo '' . $row["value_sum"] . '';
}
} else {
echo '0';
}
So this code gets the values without any issue, but when I place "else" it should give me value 0 but does not give me anything.
Any idea on how I can solve this without changing my code so far as much?
Using PDO would it be something like this:
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$pdo = new PDO($dsn, "username", "password", [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$stmt = $pdo->prepare('
SELECT SUM(count)
FROM `table_example`
WHERE `user` = :user
AND `status` = "1"'
);
$stmt->bindParam(':user', $_SESSION["user"], PDO::PARAM_STR);
$stmt->execute();
$sum = $stmt->fetchColumn();
echo $sum;
You don't need to write any loop or previous check in order to get the SUM value.
You are doing a SUM query which will always have a result row.
SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'
You might want to check the SUM(count) = 0 where you can do it in your while loop
while ($row = mysqli_fetch_array($request)) {
if (!empty($row[0])) {
echo $row[0]; // sum not 0
} else {
echo '0';
}
}
Your are using mysqli_fetch_array which returns array with both numeric and associative indexes instead of just associative array. You should use mysqli_fetch_assoc or mysqli_fetch_array with 2nd parameter resulttype as mentioned in docs.
resulttype This optional parameter is a constant indicating what type of array should be produced from the current row data. The
possible values for this parameter are the constants MYSQLI_ASSOC,
MYSQLI_NUM, or MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave
identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave
identically to the mysqli_fetch_row() function. The final option
MYSQLI_BOTH will create a single array with the attributes of both.
https://www.php.net/manual/en/mysqli-result.fetch-array.php
https://www.php.net/manual/en/mysqli-result.fetch-assoc.php
As per OP's request.
Here is your code with some changes.
<?php
$user = $_SESSION["user"];
$systems = mysqli_connect("localhost", "root", "", "testdatabase");
$query = mysqli_real_escape_string($systems, "SELECT SUM(count) AS value_sum FROM tableexample WHERE user = '$user' AND status = '1'");
$request = mysqli_query($systems, $query) or die(mysqli_error($systems)); // Added die for dev env. You can choose how you want to deal with db query error.
if (mysqli_num_rows($request) > 0) {
// Just replaced mysqli_fetch_array with mysqli_fetch_assoc
while ($row = mysqli_fetch_assoc($request)) {
echo '' . $row["value_sum"] . '';
}
} else {
echo '0';
}
Also, as you are getting 0 it seems that your if (mysqli_num_rows($request) > 0) is not returning true. Might be due to some error in db query, you may want to check that again.
Edit 04-04-2020:
Updated info about indexes of returned array by mysqli_fetch_array.
Added mysqli_real_escape_string for $query.
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
}
I'm working on something a bit more for myself, thats for another website that I own. It involves a lot of groups with permissions and such, and right now i have a function that looks like this
function hasPermission($user, $permission){
global $connection;
$sql = "SELECT * FROM admins WHERE `ID` = '". $user ."'";
$rs = $connection->query($sql);
if ($rs){
$user = $rs->fetch_array(MYSQL_ASSOC);
$userRank = $user['Rank'];
$sql = "SELECT * FROM `ranks' WHERE `RankName` = '". $userRank ."'";
$rs = $connection->query($sql);
if ($rs){
$rank = $rs->fetch_array(MYSQL_ASSOC);
if ($rank[$permission] == 1){
return true;
}
else{
return false;
}
}
}
else{
echo($connection->error);
}
}
Then when I call the function with the parameters set like this if (hasPermission($_SESSION['ID'], 'IsFullAccess') == true) it returns false, and I get my custom error message saying I don't have permission. And yes, in my database, the "IsFullAccess" column is set to 1 for that rank.
What am I doing wrong here?
After reading your code, it seems like you're not familiar with sql's JOIN:
your query looks something like this:
$sql= "SELECT r.$permission as p FROM admins a JOIN ranks r ON a.rank=r.RankName WHERE a.ID=$user";
$rs = $connection->query($sql);
if (!$rs)
return false;
$hasPermission = $rs->fetch_array(MYSQL_ASSOC);
return $hasPermission['p'];
(keep in mind sql injection)
Make sure that the db returns the result you expect before testing it within php
Try to use hasPermission($_SESSION['ID'], 'IsFullAccess') == 1) instead of hasPermission($_SESSION['ID'], 'IsFullAccess') == true). (true should be convert to 1)
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());
}
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