Counting up array results from mysql - php

i've got a problem with my php script. I want to check my script if there is anything in array and if there's no to echo a message but when array is empty it just don't echo nothing.
That's my code:
include("mysql_connect.php");
$name = $_POST['playerName'];
$users = mysql_query('SELECT * FROM playerdata WHERE username LIKE "'.$name.'%"');
if($name==""){
echo 'Type in player name!';
}else{
while($usersList= mysql_fetch_assoc($users)){
if(!array_count_values($usersList)){
echo 'Player not found';
}else{
echo $usersList['username'].', ';
}
}//While end.
}//If name is empty end.

As mentioned, you have to check for rows before the loop.
$rows = mysql_num_rows($users);
if($rows==0) echo "No rows..";
else {
foreach() {

The problem seems is that, if a user enters a invalid name, the while loop does not execute, as the query simply cannot find any rows, the code should be as follows
include("mysql_connect.php");
$name = $_POST['playerName'];
if( $name === "" ){
echo 'Type in player name!';
} else {
$users = mysql_query('SELECT * FROM playerdata WHERE username LIKE "'.$name.'%"');
if ( mysql_num_rows($users) == 0) {
echo "Invalid Player name provided";
} else {
while($usersList= mysql_fetch_assoc($users)){
{
echo $usersList['username'].', ';
} //While end.
}
}//empty name
Notes:
I have re-formatted the code as it looked ugly
The query is executed only if a user provides some text for name, why execute the query when the name is empty !

instead of
if(!array_count_values($usersList)){
use
if(empty($usersList)){

Your while loop wont be executed if $users is empty, so the condition:
if(!array_count_values($usersList)){
echo 'Player not found';
}
will never be met because it is contained in a loop which will never run.

Related

Executing mysqli_query works but it does not return exact row given in WHERE CLAUSE

The query executes .. but let's say for example the user changed the value of $_GET['sub'] to get an id which is not in the database , lets say for example : 60 .
it should print "NOT FOUND" instead it prints found ! Why is that ?
$main = new MainClass();
$subid = mysqli_real_escape_string($main->MsqlConRes,$_GET['sub']);
if (is_numeric($subid))
{
$main->query = mysqli_query($main->MsqlConRes,"SELECT * FROM subjects WHERE id = ".$subid."") or die(mysqli_error());
if ($main->query)
{
echo'Found';
}
else
echo'Not Found !';
}
else
$main->errors(404);
use mysqli_num_row() in if
if (mysqli_num_row($main->query)>0)
{
echo'Found';
}
else
echo'Not Found !';
Since query is executing properly so if ($main->query) will always be true

php "if" without answer

This problem should be simple to resolve, but I can't...
After a request, a condition has to verify if the concerned article really exists, verifying the URL ($_GET).
My code : ( a testing file with simple echos )
$id = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?');
$id->execute(array($_GET['numArticle']));
while ($dataID = $id->fetch()) {
if (empty($dataID) or $dataID == null or !isset($dataID)) {
echo 'No content';
} else {
echo 'Can load the page';
}
}
$id->closeCursor();
The page behaviour : "can load the page" is writing when numArticle is right, but if it is not, nothing appears, neither an error message or something.
Any idea/advice? Thank you.
One way to do this is by checking the number of rows returned by mysqli:
$id = $bdd->prepare('SELECT content FROM articles WHERE idArticle = ?');
$id->execute(array($_GET['numArticle']));
if($id->num_rows > 0){
echo "can load page";
}else{
echo 'No content';
}
You can use fetchAll() function of PDO then run a foreach loop on data:
$rows = $id->fetchAll(PDO::FETCH_ASSOC);
if(!empty($rows)){
foreach($rows as $row){
echo "content";
}
}
else{
echo "No Content";
}
Assuming you are using Pdo, it looks like you want to be using Pdo's fetchColumn method.
<?php
$stmt = $db->prepare('SELECT content FROM articles WHERE idArticle = ? LIMIT 1');
$stmt->execute(array($_GET['numArticle']));
if ($result = $stmt->fetchColumn()) {
echo 'A result';
} else {
echo 'Db fetch returned false (or could be a string that evaluates to false).';
}

Display result of Pdo

Hi i have an slight problem i'm trying top geht tow Results of My pdo query and Print Them but No such luck i've probably just Made a Stupid mistake i'm Not seeing The query seems to be finde so it does make a difference if the name is in the database (and it makes a difference if you put it in quotes) probably the variables are getting a null value or something...
$username="xxx";
$firstname="xxx";
$check=0;
if (isset($_GET['u'])){
$username=strip_tags(#$_GET['u']);
if (ctype_alnum($username)){
$check=$stmt=$link->prepare("SELECT * FROM
users WHERE username = ?");
$stmt->execute(array($username));
$check=$stmt->fetchAll();
if(count($check)==1){
$get=$stmt->fetch(PDO::FETCH_BOTH);
echo "$get";
$username =$get["username"];
$firstname = $get["first_name"];
}else{
echo "<h2> User does not exist!</h2>";
exit();
}
}
}
?>
<h2>Profilepage for: <?php echo "$username"; ?></h2>
<h2>First name: <?php echo "$firstname"; ?></h2
$stmt->fetchAll() is fetching all the results of the query. Once this is done, there are no more results available for $stmt->fetch() to fetch. You should get the data from the $check array.
if (count($check) == 1) {
$get = $check[0];
$username = $get["username"];
$firstname = $get["first_name"];
} else {
echo "<h2> Username does not exist </h2>";
exit();
}
Or you could just replace the fetchAll with fetch.
$stmt->execute(array($username));
$get = $stmt->fetch(PDO::FETCH_ASSOC);
if ($get) {
$username = $get["username"];
$firstname = $get["first_name"];
} else {
echo "<h2> Username does not exist </h2>";
exit();
}
Also, echo "$get" makes no sense. $get is an array, you can't echo it, you need to use print_r($get) or var_dump($get).

PHP MySQL IF .. ELSE (Else Not Displaying Anything)

I am trying to go through all the records in a table and display something for all the records which has a match on the SQL and display something else for the record that don't have a match.
So I'm doing this:
$result = mysqli_query($con,"SELECT * FROM myTable WHERE id='$my_id' ");
while($row = mysqli_fetch_array($result)) {
if (!empty($row['id'])) {
echo 'Match Exists!';
} else {
echo 'There is NO Match';
}
}
My problem is that there is No echo for the non matches although there is for the matches.
So, I'm getting "Match Exists!" for the matches but no "There is NO Match" for the non matches.
What I'm I doing wrong here?
SELECT * FROM myTable WHERE id='$my_id
here you are checking if there exists any row where the ids matches so your code below loses his property:
if(!empty($row['id'])) {
echo 'Match Exists!';
} else {
echo 'There is NO Match';
}
You are already verifing if exists so there will not be any empty id.
Try this
<?php
$result = mysql_query($con,"SELECT * FROM myTable WHERE id='$my_id' ");
$num=mysql_num_rows($result);
if ($num!=0)
{
echo 'Match Exists!';
} else {
echo 'There is NO Match';
}
?>
OR
<?php
$result = mysql_query($con,"SELECT * FROM myTable WHERE id='$my_id' ");
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$query=$result = mysql_query($con,"SELECT * FROM myTable WHERE id='$id' ");
$num=mysql_num_rows($query);
if ($num!=0)
{
echo 'Match Exists!';
} else {
echo 'There is NO Match';
}
}
?>
If there are no matches, $row will evaluate to FALSE (because no rows are returned). If you have to do it with a while loop, try do { ... } while (...);, like below.
The difference is that the while() condition is checked after the first iteration.
$result = mysqli_query($con,"SELECT * FROM myTable WHERE id='$my_id' ");
do {
$row = mysqli_fetch_array($result);
if (!empty($row['id'])) {
echo 'Match Exists!';
} else {
echo 'There is NO Match';
}
} while(!empty($row['id']));
You have no matches because of your query.
SELECT * FROM myTable WHERE id='$my_id'
The above will fetch only matching records.
Maybe you should alter your query or the line
if (!empty($row['id']))
and check for another field that might be empty
Your query explicitely filters out "non-matching" rows:
WHERE id = '$my_id' -- neither rows having "id != $my_id"
-- nor rows with empty "id" are fetched by this query
You probably want to remove the WHERE condition from your query, and test for if($row['id'] === $my_id) in your PHP loop.
Try to remove "spaces" with trim:
if (!empty(trim($row['id']))) {
echo 'Match Exists!';
}

PHP MYSQL compare database value to POST value

This is a really simple one, I just can't get my head around it sorry. I have this PHP code which picks up my form value, then compares it with the value stored in the database. That works fine.
However I am not sure how to write this logic in terms of this query:
If posted value = database value {
// do something } else { // do something else }
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
$row = mysqli_fetch_assoc($result);
echo $row['order_id'];
}
SOLVED:
Solved the question, was a silly one I know! Just needed this at the end of the code:
if($order_id === $row['order_id']) {
echo 'found';
} else {
echo 'not found';
}
Try
If ($result->num_rows === 1) { do something } else { do something else }
Since you did the business logic in your query you can just use
if( ! is_null($row)) {
// do
} else {
// nothing
}
Did I read too much into "If posted value = database value "? Are you just referring to the order_id?
if ($row['listingName'] == $_POST['frm_listingName']) {
// something
}
else {
//something else
}
Check this code:
if (empty($_POST['order_id']) === false) {
// prepare data for inserting
$order_id = htmlentities(trim($_POST['order_id']));
$order_id = preg_replace("/[^0-9]/","", $order_id);
$result = mysqli_query($con,"SELECT * FROM listings WHERE order_id = $order_id");
if(mysqli_num_rows($result)>0)
{
//Match found. do something.
}
else
{
//No match found. do something.
}
}
N.B. In place of mysqli_num_rows($result) you can also use $result->num_rows

Categories