I'm using $id = intval( $_REQUEST['id'] ); , to get ID of the news/posts on my website, and the link to the news is article.php?id=XXX. So when someone type ?id=1 and there's nothing it's empty, no posts, it should go to index page (index.php) instead showing blank page. Is it possible? I've tried via isset something but it didn't worked. Can anyone help me with this, please.
if($ArticleSQL = $mysqli->query("SELECT * FROM articles WHERE id='$id' ")){
...
}
You can check the number of results with $ArticleSQL->num_rows.
So your code will now be:
$ArticleSQL = $mysqli->query("SELECT * FROM articles WHERE id='$id' ");
if($ArticleSQL->num_rows > 0) {
$article = $ArticleSQL->fetch_array();
//show the article here
} else {
//redirection:
header("Location: index.php");
}
You need to check if the query found anything. Your code simply checks if the query succeeded. A query which returns no rows is NOT a failure. It's a perfectly valid result set that happens to have no rows in it.
$result = $mysqli->query(...);
if ($result->num_rows > 0) { ... found something ... }
Related
I am creating PHP products view details page this script disaply like this URL
http://localhost/zblog/source.php?srcid=1 I want to get title URL from id
like this
http://localhost/zblog/source.php?title=some-title
Here is my code
<?php
include("config.php");
if(isset($_GET['srcid'])) {
$srcid = $_GET['title'];
if($stmt = $con->prepare("SELECT * from products WHERE srcid=?")){
$stmt->bind_param("s", $srcid);
$stmt->execute();
}
$result = $con->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
}
}
}
?>
Your logic is skewed, if the URL is:
http://localhost/zblog/source.php?srcid=1
then you aren't passing the title but if the URL like this:
http://localhost/zblog/source.php?title=some-title
then your if statement will never run because:
if(isset($_GET['srcid'])) {
it relies on $_GET['srcid'].
If you want to use the title then amend that if statement to look for $_GET['title'] instead of $_GET['srcid'] or, try passing both parameters in the URL together.
This would only work if your url included ?srcid=1&title=some-title
This is because of your if statement which only runs if srcid is set.
change
if(isset($_GET['srcid'])) {
to
if(isset($_GET['title'])) {
I'm trying to make an admin page and allow only users with role 2 for some reason its not giving me the information I expected.
<?php
session_start();
require_once('includes/mysql_config.php');
$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: login.php');
$user = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']) || false;
if($user['role'] == '2'){
echo "Hello $user['name']";
}
else {
header('location: index.php');
}
?>
When I do vardump($user) its giving me the output 1.
When I echo the $_SESSION['id'] it is giving me the right id (the session id is the same as user id).
Right now what you have done is, you just executed the query and had the resultset stored in $user. You need to fetch the results from the Result Set.
$user = mysqli_fetch_array($user);
Now it should work as expected.
Update: You should also handle the following:
Sanitization: Make sure you use ' for the values and ` for the column names. Also use mysqli_real_escape_string() for escaping some obvious stuff.
Validation: That's the next most important. Try checking if the resultset has any rows returned. You can do by using mysqli_num_rows($user) > 0 or precisely in your case, mysqli_num_rows($user) == 1.
Variables: Here in the example, I have used the same $user for the Result Set as well as the row. It is always better to have two separate variables, say, $userRes (for result set) and $userData (for the fetched data).
Hope this should answer your question.
After a successful select query mysqli_query() will return an mysqli_result object. You have to itterate over that to get your results. For example:
$user = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']) || false;
if(user ){
// Cycle through results
while ($row = user ->fetch_object()){
$users[] = $row;
}
$user->close();
}
You're not fetching the results... If you check the manual, and look for the return value of mysqli_query(), you'll find:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE
So go ahead and fetch it:
//$user = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']) || false; // I'm unfamiliar with this || false stuff.
$result = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']);
$user = mysqli_fetch_array($result);
It's also a good idea to sanitize your input (in order to prevent SQL-injection) and to check whether there are any results with mysqli_num_rows().
I have an issue with an if logic statement that I cant seem to figure out and am looking for someone wiser than me to point out the error of my ways.
Below is my code:
$sql = "select count(id) from tempaddress where postcode='".$values['PostCode']."'";
$rs = CustomQuery($sql);
$data = db_fetch_array($rs);
print_r($data);
if ($data > 0)
{
//Redirect to Address Selection Page
$cid=$keys['CompanyId'];
header("Location: UpdateAddress_edit.php?editid1=".$cid);
exit();
}
else echo "<script>alert('No Addresses Found. Please Contact Administrator')</script>";
What this is supposed to do is look up how many results are found and if the answer is >0 then it takes it to next page, if not it gives you a popup message.
The count function works, but for some reason, even if the result is 0, it still takes the process to next page, see here http://prntscr.com/58949d, I have put a false post code in, and it should say, no!
Can anyone see what is going wrong, or point out a way to use if record exists then {}?
I am using PHP with MS Access.
Firstly, alias your expression:
$sql = "select count(id) as addressCount from tempaddress where postcode='".$values['PostCode']."'";
Then use it in the if statement
if ($data['addressCount'] > 0){
...
}
else{
}
try if($data[0] > 0 )since you're fetching as array
It should be like -
if ($data['Expr1000'] > 0)
My database fields are not populating but the page is confirming that it exists. So the first SQL is working, but the second is not pulling the info. If i take the page check out. It doesn't find the page and redirects to page_not_found. Am I going about this correctly? What am i doing wrong here?
//get page url and query db
$this_page = $_GET['page'];
$this_page = escape_data($_GET['page']);
//Make sure page exist
$SQL_page_exist = "SELECT page_title FROM learn_more WHERE page_title = '$this_page'";
$SPE_result = mysql_query($SQL_page_exist);
if(mysql_num_rows($SPE_result) == 0)
{
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=page_not_found.php">';
}
else {
$SQL =
"SELECT * FROM learn_more AS lm
INNER JOIN learn_more_to_reference_key AS lmtrk
ON lm.id = lmtrk.learn_more_id
INNER JOIN reference_keys AS rk
ON rk.keys_id = lmtrk.reference_key_id
WHERE page_title = '$this_page'";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result));
{
$id = $db_field['ID'];
$main_title = $db_field['main_title'];
$main_content = $db_field['main_content'];
$reference_keys = $db_field['keys_href'];
$sub_title = $db_field['sub_title'];
$sub_content = $db_field['sub_content'];
}
}
mysql_close($dbc);
You should remove the semi-colon after your while statement since it won't execute the following enclosure (meaning your query is fine, but the while statement is invalid).
Also, I'm not sure, but the statement:
$id = $db_field['ID'];
Might generate an error if the mysql field is 'id' (lowercase). While MySQL isn't (usually) case sensitive, php array keys are, so it may be that the key is only available as 'id' and not 'ID'...
Turns out that an empty field from a relational db table (just 1 black field) which is set to not null was causing this undefined break error.. ON ALL PAGES except the home page..
Thank you to all the people who tried to help me.
Trying to display a message if no results found in the search query.
Here is a brief example of my code.
$sql = "SELECT * FROM details WHERE ID =1"
$res =& $db->query($sql);
if (PEAR::isError($res)) {
die($res->getMessage());
}
while($row = $res->fetchRow())
{
echo 'results'
{
Any help would be greatly appreciated! Thanks
DB_result has a method called numRows(), so you could check
if($res->numRows() == 0)
http://pear.php.net/package/DB/docs/latest/DB/DB_result.html#methodnumRows
Get the number of rows in a result set
Return: the number of rows. A DB_Error object on failure.
And you don't need to worry about DB_Error since it was already checked at
PEAR::isError($res)