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).';
}
Related
/MY CODE/
The if part is working properly but else is not working.
i even tried $variable instead of direct echo but still it is not working 'else'
Updated
<?php
$db = new mysqli('localhost', 'root' ,'', 'timeline');
if(!$db) {
echo 'Could not connect to the database.';
} else {
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
if(strlen($queryString) >0) {
$query = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10");
if(isset($query)) {
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some'; // this part is not working
}
} else {
// do nothing
}
} else {
echo 'There should be no direct access to this script!';
}
}
?>
help me out.....
even read lots of like problem on stackoverflow but no real return
If you are using mysqli::query then your if(isset($query)) statement will always be evaluated as true, as $query would be either FALSE or a mysqli_result object. isset returns TRUE for both these values, so your else code will never be called.
Documentation on isset:
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Use if($query !== false) instead.
Update
It also seems like you are checking $query to see whether or not there was a hit in the database. You need to check the number of rows in the result for that, e.g:
if ($query !== false && $query->num_rows > 0) {
// Query was ok and at least one row was returned
}
else {
// Will be reached if query was bad or there were no hits
}
Try
if($query_run = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10")){
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some';
}
im having a simple mysql/php problem. so i am adding in Image titles for my website, and the code is displayed below. It works, but when you dont put a image, it shows up as blank. I need it to show up as 'No image title' (bc i will use this for image description to). It basically gets the image name, then takes the title from that row.
So how do i do it? :/ im still very new to PHP.
<?php
if (isset($imgtitleset))
{
$sql = "SELECT image_title FROM images WHERE image_name = '$image_main'";
$result = mysql_query ($sql);
while ($row = mysql_fetch_array($result))
{
$imgtitle= $row["image_title"];
echo "$imgtitle";
}
}
else {
echo 'no image title';
}
?>
Change the while loop like so:
while ($row = mysql_fetch_array($result)) {
$imgtitle= $row["image_title"];
if($imgtitle != '') {
echo $imgtitle;
} else {
echo 'no image title';
}
}
Also, I'm not sure what the $imgtitleset variable is for, but you can probably get rid of the if statement checking to see whether it's set.
Edit: the whole thing should probably look like this:
<?php
$sql = "SELECT image_title FROM images WHERE image_name = '$image_main'";
$result = mysql_query ($sql);
while ($row = mysql_fetch_array($result)) {
$imgtitle= $row["image_title"];
if($imgtitle != '') {
echo $imgtitle;
} else {
echo 'no image title';
}
}
?>
This all depends on what $imgtitleset is equal to. It is clearly set against something:
while ($row = mysql_fetch_array($result)) {
$imgtitle = $row["image_title"];
if (isset($imgtitle))
echo "$imgtitle";
else
echo 'no image title';
}
This would mean if nothing was found in the database then it will echo the no image title. However like I said, this could depend on what $imgtitleset is, maybe post the code for that?
If you only expect the select to return a single row, then use if rather than while and return the error on else:
<?php
if (isset($imgtitleset))
{
$sql = "SELECT image_title FROM images WHERE image_name = '$image_main'";
$result = mysql_query ($sql);
if ($row = mysql_fetch_array($result))
{
$imgtitle= $row["image_title"];
echo "$imgtitle";
}
else {
echo 'no image title';
}
}
?>
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Alternative for mysql_num_rows using PDO
^ I believe it isn't the same question - The other authors code is different to mine, which needed a different answer. I successfully got my answer from this post and marked it as answered. Everything is working fine now (no help from the other 'duplicate' thread.
I want to display a "No Client Found" message if no results are found, Is there a PDO method to the following code?:
$result = mysql_query($sql) or die(mysql_error()."<br />".$sql);
if(mysql_num_rows($result)==0) {
echo "No Client Found";
I tried the following...
<?php
$db = new PDO('mysql:host=localhost;dbname=XXXXXXXXXXXX;charset=utf8','XXXXXXXXXXXX', 'XXXXXXXXXXXX');
$query = $db->query('SELECT * FROM client');
if ($query == FALSE) {
echo "No Clients Found";
}
else
{
foreach($query as $row)
{
<some code here>
}
}
?>
Am I missing something?
I've read: http://php.net/manual/en/pdostatement.rowcount.php but hasn't helped
<?php
$db = new PDO('mysql:host=localhost;dbname=XXXXXXXXXXXX;charset=utf8','XXXXXXXXXXXX', 'XXXXXXXXXXXX');
$query = $db->query('SELECT * FROM client WHERE ID = 10');
if ($query->rowCount() != 1) {
echo "No Clients Found";
}
else
{
foreach($query as $row)
{
<some code here>
}
}
?>
In PDO, rowCount method is used to count the returned results. Your query must select some thing unique, like an email address or username if you want to check for unique existence, else, if you want at least find one row, change the condition to this:
if ($db->rowCount() == 0)
There is a tutorial: PDO for MySQL developers.
PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement in some databases. Documentation The code below uses SELECT COUNT(*) and fetchColumn(). Also prepared statements and try & catch blocks to catch exceptions.
<?php
// Get parameters from URL
$id = $_GET["client"];
try {
$db = new PDO('mysql:host=localhost;dbname=XXXX;charset=utf8', 'XXXX', 'XXXX');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare COUNT statement
$stmt1 = $db->prepare("SELECT COUNT(*) FROM client WHERE client = ?");
// Assign parameters
$stmt1->bindParam(1,$id);
$stmt1->execute();
// Check the number of rows that match the SELECT statement
if($stmt1->fetchColumn() == 0) {
echo "No Clients Found";
}else{
//echo "Clients Found";
// Prepare Real statement
$stmt2 = $db->prepare("SELECT * FROM client WHERE client = ?");
// Assign parameters
$stmt2->bindParam(1,$id);
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
$stmt2->execute();
while($row = $stmt2->fetch()) {
//YOUR CODE HERE FROM
// Title
echo '<div id="portfolio_detail">';
//etc.etc TO
echo '<div><img src="'."/client/".$row[client].'_3.png"/></div>';
echo '</div>';
}//End while
}//End if else
}//End try
catch(PDOException $e) {
echo "I'm sorry I'm afraid you have an Error. ". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", myfile.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
//Close the connection
$db = null;
?>
This should be simple.... but it's taking a while... Here's the code that's not working (it either shows nothing or the blank state message each time). $show image is the query and I know it's running fine.
// BLANK STATE TOGGLE
$result = mysqli_fetch_array($showimage, MYSQLI_ASSOC);
if($result == ''){
echo '<p>Sorry- no image.</p>';
}
else {
echo '<p>There is an image!</p>';
}
}
If you only want to check for the existence of rows in the result from your query, why don't you simplify it like this
// $db is your MySQLi connection object
$query = 'SELECT COUNT(1) FROM `table` WHERE `something` = ?';
$stmt = $db->prepare($query);
$stmt->bind_param('s', $something);
$stmt->execute();
$stmt->bind_result($rowCount);
$stmt->fetch();
$stmt->close();
if ($rowCount > 0) : ?>
<p>There is an image!</p>
<?php else : ?>
<p>Sorry- no image.</p>
<?php endif ?>
mysqli_fetch_array returns null if there is no match in the database. So you need to check for null.
You may need to try this:
if $showimage is your query ..
//This should run fine
//$link is ur connection
$new_result = mysqli_query($link,$showimage);
$result = mysqli_fetch_array($new_result, MYSQLI_ASSOC);
if($result == null){
echo '<p>Sorry- no image.</p>';
}
else {
echo '<p>There is an image!</p>';
}
}