A weird while issue - php

I have 3 whiles in the code below. Before this I had just 1 while but after expanding the CMS it doesn't want to display the content anymore, I'm not sure what is causing the bug.
<?php
$stmt = $dbConnection->prepare('SELECT * FROM paginas WHERE public="1"');
$stmt->execute();
$result = $stmt->get_result();
$url = $dbConnection->prepare('SELECT * FROM websettings WHERE setting="url"');
$url->execute();
$urlresult = $url->get_result();
$startpagina = $dbConnection->prepare('SELECT * FROM websettings WHERE setting="startpagina"');
$startpagina->execute();
$startresult = $startpagina->get_result();
if(mysqli_num_rows($result) > 0) {
while ($row = $result->fetch_assoc()) {
while ($urlrow = $urlresult->fetch_assoc()) {
while ($startrow = $startresult->fetch_assoc()) {
if(!empty($_GET[$urlrow['value']])) {
if(isset($_GET[$urlrow['value']]) && $_GET[$urlrow['value']] == $row['name']) {
?>
<h1><?php echo $row["heading"]; ?></h1>
<?php echo ubbreplace($row["content"]); ?>
<?php
}
} else {
header("Location: ?" . $urlrow['value'] . "=" . $startrow["value"]);
}
}
}
}
} else {
echo "Er zijn nog geen pagina's aangemaakt.";
}
?>
Can someone please help me out? I'm really trying to fix it, nothing really works.
SOLUTION
<?php
$stmt = $dbConnection->prepare('SELECT * FROM paginas WHERE public="1"');
$stmt->execute();
$result = $stmt->get_result();
if(mysqli_num_rows($result) > 0) {
while ($row = $result->fetch_assoc()) {
$url = $dbConnection->prepare('SELECT * FROM websettings WHERE setting="url"');
$url->execute();
$urlresult = $url->get_result();
while ($urlrow = $urlresult->fetch_assoc()) {
$startpagina = $dbConnection->prepare('SELECT * FROM websettings WHERE setting="startpagina"');
$startpagina->execute();
$startresult = $startpagina->get_result();
while ($startrow = $startresult->fetch_assoc()) {
if(!empty($_GET[$urlrow['value']])) {
if(isset($_GET[$urlrow['value']]) && $_GET[$urlrow['value']] == $row['name']) {
?>
<h1><?php echo $row["heading"]; ?></h1>
<?php echo ubbreplace($row["content"]); ?>
<?php
}
} else {
header("Location: ?" . $urlrow['value'] . "=" . $startrow["value"]);
}
}
}
}
} else {
echo "Er zijn nog geen pagina's aangemaakt.";
}
?>

Get Rid of the "dynamic" parametername - hide it behind a parameter you can access in a static way:
?page=index
becomes
`?p_mode=page&p_selection=index`
or whatever.(Do you REALLY need page to be dynamic? - I guess not.)
Then, you can easily use a single query (Imagine the first 2 parameters are not hardcoded, but used from the GET-Parameters p_mode and p_selection):
set #setting_name = "page";
set #setting_value = "index";
SELECT
p.*
FROM
paginas p
right JOIN
websettings ws
ON
ws.`value` = p.`name`
WHERE
p.`public` = 1 AND
ws.`setting` = #setting_name AND
ws.`value` = #setting_value;
http://sqlfiddle.com/#!9/ce97a/2
However, note that your "setting name" is useless in this tiny example, as it only joins on the value.
(See this example, leading to a wrong result: http://sqlfiddle.com/#!9/d4abb0/1)
So - if you want different keys, add them to the paginas table, make them (and the value) a unique pair:
public | heading | content | key | value
1 Test Test mode index
1 Test 2 Test 2 anotherKey index
and query them in a single run.
Add the End: Please read this post: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem
Try to ask about your actual problem rather than the solution you think might work in the future.

Related

Why is 400030 not giving out the logic that its greater than 400000?

I wrote a code to echo "limit reached" if A is greater than B. But if A is 400030 and B is 400000 it shows no output. If A is further greater than that, let say 400060 or any number higher than that, it shows the output.. Please how do I explain that? The code snippet to demonstrate what I mean is....
<?php
include_once('db.php');
error_reporting(E_ALL | E_WARNING | E_NOTICE);
ini_set('display_errors', TRUE);
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(!isset($_SESSION['login'])) {
echo ("<script>location.href='../clogin/'</script>");
die();
}
if(isset($_POST['transfer'])) {
$username = $_SESSION['login'];
$transAmount = $_POST['transAmount'];
$totalTrans = $transAmount + 30;
$sql = "SELECT * FROM customer WHERE username = ?";
$stmt = $connection->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
if(!$result) {
die('ERROR:' . mysqli_error($connection));
}
$count = $result->num_rows;
if($count == 1) {
while ($row = $result->fetch_assoc()){
$accTrans = $totalTrans + $row['dailyTrans'];
$sql2 = "UPDATE customer set dailyTrans=? WHERE username=?";
$stmt = $connection->prepare($sql2);
$stmt->bind_param('is', $accTrans,$username);
$stmt->execute();
if(!$stmt) {
die('network problem');
}
if($row['dailyTrans'] >= $row['dailyLimit']) {
echo '<script>swal.fire("FAILED!!", "<strong>You have reached the total amount you can send per day.</strong><hr><br/><i>Visit your bank to increase transfer limit.</i>", "error");
window.setTimeout(function(){
window.location.href = "transfer1.php";}
, 1700);
</script>';
//exit();
} else {
echo"";
}
}//while loop
}//count
}//submit
?>
My question Summary Again
The value for $row['dailyTrans'] is 400030 and the value of $row['dailyLimit'] is 400000
This is suppose to echo out the error but fails... if $row['dailyTrans'] is greater than 400030, it echoes out. What is the logic behind that?.
Please be nice with your comments as usual. Thanks . Both Value are integers!!
Looks to me that you are adding $_POST['transAmount'] after querying the database for the user.
To get the current dailyTrans you will need to either
Select from customer again
(fetching the updated dailyTrans)
OR
compare dailyLimit to $accTrans ::
(if ($accTrans >= $row['dailyLimit'])

PDO and While function in PHP not working

Hey guys so i really have a problem in php and i have been working on it for like an hour and i can get it to work. So in my database i have two tables:
usuarios and menus
So each user have a menu assigned like this:
usuarios
id email ....... menus
1 email ...... 1,2,3,4
where 1,2,3,4 is text that i will explode and convert it into an array so latter i can get the menus checking the menu id's.
menus
id url .....
1 profile ..........
2 messages ..........
3 log out ..........
4 support ..........
I dont know why it is not working, please help.
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));}
// Checks the user id from his session (session has been already started in headers)
if($stmt->rowCount() > 0){
$row = $stmt->fetch();
$menus = $row['menus'];
//Gets the menus
$menus = explode(",", $menus);
//Converts the text into an array.
$i = 0;
$menusize = sizeof($menus);
//Checks how big is $menus array
$menusize = $menusize -1;
//This is because $i=0 and not 1
while ($i == $menusize) {
try{
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
$stmt->execute(array(':menus'=>$menus[$i]));
$row = $stmt->fetch();
if ($section==$row['url']) {
echo '<li class="liselected"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}else{
echo '<li class="menuelement"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
$i++;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Here is the problem, in this while
} else {
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}else{
header("Location:index.php");
}
?>
I have checked and what happends is that $i doesnt seems to be incrementing, i have been working on it but nothing seems to do it.
Thank you all for your support!
You should do it a little bit differently altogether, like storing the menu's in different rows but for now:
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
# When you set the $_SESSION['id'] and you're sure it's sanitized you don't have to prepare a query. Instead execute it directly.
# Preparing is useful for user submitted data or running the same query more then once with different values (seen below)
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
// This part of the code does not match your description of your database.
$row = $stmt->fetch();
$menu = explode(",", $row['menus']);
// end
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
try{
foreach($menu as $value){
$stmt->execute(array(':menus'=>$value));
$row = $stmt->fetch();
$css_class = ($section == $row['url']) ? 'liselected' : 'menuelement';
echo '<li class="'.$css_class.'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
} else {
header("Location:index.php");
}
?>
Please note that I only prepared the query once, this is the proper way to do it. Preparing takes server performance, but once prepared you can rebind the values.
Also, I changed the loop to a foreach loop, easier to maintain.
There where also some bracket issues in the code, my advice always code in the same way so these issues are easy to spot.

Passing php variables through pages / sql

i have the following information displayed
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0)
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
?>
as you can see i have created a game_details page which will display that specific Game_id when the image is clicked
im having trouble understanding how to pull the data out from that game_id in sql on the other page.
here is my attempt on the game_details page
<?php
if (!isset($_GET['$game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id={$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['$game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
This attempt is giving me the "invalid category ID" error
Would appreciate help
There are a few issues with your code.
Let's start from the top.
['$game_id'] you need to remove the dollar sign from it in $_GET['$game_id']
Then, $row['$game_id'] same thing; remove the dollar sign.
Then, game_id={$game_id}' will throw a syntax error.
In your first body of code; you should also use proper bracing for all your conditional statements.
This one has none if (mysqli_num_rows($result) > 0) and will cause potential havoc.
Rewrites:
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0){
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
}
?>
Sidenote for WHERE game_id='{$game_id}' in below. If that doesn't work, remove the quotes from it.
WHERE game_id={$game_id}
2nd body:
<?php
if (!isset($_GET['game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id='{$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
Use error checking tools at your disposal during testing:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
You want to be using $_GET['gameid'] as that's the parameter you passed.
You are calling for game_id when the link to go to game_details.php has the variable gameid. Either change the parameter in the link to game_id or call for gameid in your $_GET['$game_id'].
Also, as Fred -ii- said, take out the dollar sign in $_GET['$game_id']

PHP mySQL search script for website

I highly appreciate that you try to help me.
My problem is this script:
<?php include("inc/incfiles/header.inc.php"); ?>
<?php
$list_user_info = $_GET['q'];
if ($list_user_info != "") {
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
$user_list = $get_user_list['username'];
$user_profile = "profile.php?user=".$user_list;
$profilepic_info = $get_user_list['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/avatar.png";
}
else {
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
if ($user_list != "") {
?>
<br>
<h2>Search</h2>
<hr color="#FF8000"></hr>
<div class="SearchList">
<br><br>
<div style="float: left;">
<img src="<?php echo $profilepic_info; ?>" height="50" width="50">
</div>
<?php echo "<h1>".$user_list."</h1>"; ?>
</div>
<?php
}
else {
echo "<br><h3>User was not found</h3>";
}
}
else {
echo "<br><h3>You must specify a search query</h3>";
}
?>
I am creating a search script that takes the mysql databse information and shows the result associated to the search query. My script is the above, but keep in mind the sql connection is established in an extern scipt.
The problem is that i want the script to first check if the user is found with the search query in the username row, and then get the entre information from that user and display it. If the user is not found with the username query, it should try and compare the search query with the name row, and then with the last name row. If no result is displayed it should then return an else statement with an error, e.g. "No user wsas found"
Yours sincerely,
Victor Achton
Do the query as Muhammet Arslan ... but just counting the rows would be faster ...
if(mysql_num_rows($get_user_info)){
//not found
}
you should add a "Limit 1" at the end if you are just interested in one result (or none).
But read about prepared statements
pdo.prepared-statements.php
This is how it should be done in 2013!
Something like this but you don't need 3 queries for this. you can always use OR in mysql statements
$handle1 = mysql_query("SELECT * FROM users WHERE username = $username"); // Username
if (($row = mysql_fetch_assoc($handle1) !== false) {
// username is found
} else {
$handle2 = mysql_query("SELECT * FROM users WHERE name = $name"); // name
if (($row = mysql_fetch_assoc($handle2) !== false) {
// name is found
} else {
$handle3 = mysql_query("SELECT * FROM users WHERE lastname = $lastname"); // Last name
if (($row = mysql_fetch_assoc($handle3) !== false) {
// last name is found
} else {
// nothing found
}
}
}
Already you did ,but you can improve it by using "AND" or "OR" on ur sql statement.
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$list_user_info' or name = '$list_user_info' or last_name = '$list_user_info'");
$get_user_list = mysql_fetch_assoc($get_user_info);
if(empty($get_user_list))
{
echo "No User was found";
}
and you should control $list_user_info or u can hacked.
Here some adapted copy pasting from php.net
Connect
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
fetch data
$stmt = $dbh->prepare("SELECT * FROM users where name LIKE '%?%'");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
the rest is your programing ...
And do some reading it's very dangerous to use copied code without understanding !

php mysql if row is empty and if isn't empty

Code:
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table`
WHERE `Username` = '$Username'
ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) { ?>
<?php if(!isset($db['article'] && $db['subject'])) {
echo "Your articles";
} else {
echo "You have no articles added!";
} ?>
<?php } ?>
So I want the rows for example(db['article'] and $db['subject']) from a specific username (see: $Username = $_SESSION['VALID_USER_ID'];) to echo the information if is not empty else if is empty to echo for example "You have no articles added!"
If is some information in the rows the code works, echo the information BUT if the rows is empty don't echo nothing, the code should echo "You have no articles added!" but this line don't appear, where is the mistake?
I tried for if !isset, !empty, !is_null but don't work.
I think what you're trying to achieve is:
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
if(mysql_num_rows($q) > 0)
{
echo "Your articles:\n";
while($db = mysql_fetch_array($q)) {
echo $db['subject']." ".$db['article']."\n";
}
}
else
{
echo "You have no articles added!";
}
?>
I don't understand. Do you have article rows with username, but without article, i.e.:
| id | user | article |
-------------------------------------
| 1 | X | NULL |
If so, you can test with:
if($db['article'] == NULL) { .... } else { .... }
Otherwise, if you don't have a row with user=x, when there are no record, mysql will return an empty result.
So, basicly, if no rows are found on selection: SELECT * FROM article_table WHERE Username = 'X';, you can test
if(mysql_num_rows($q) > 0) { .... } else { .... }
However, mysql_ functions are not recommended anymore. Look at prepared statements.
You have a logic error in your if statement -- what you want is to check if both the article and subject are set.
With your current code, you compare $db['article'] with $db['subject'], and check if the result is set. You need to change it a bit :
Instead of :
if(!isset($db['article'] && $db['subject'])) {
Try:
if(isset($db['article']) && isset($db['subject'])) ...
I would do something like this:
$articles='';
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) {
if(isset($db['article']) && isset($db['subject'])) {
$articles .= $db['article']."<br/>";
}
}
if($articles != ''){
echo $articles;
}
else{
echo "No articles";
}
?>
fastest way to achieve what you want is by adding a variable that will verify if the query returned any rows:
<?php $Username = $_SESSION['VALID_USER_ID'];
$i = 0;
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) {
$i = 1;
if(!isset($db['article'] && $db['subject'])) { echo "Your articles"; } ?>
<?php }
if ($i == 0) echo "You have no articles";
?>
You tried to echo "no articles" in the while loop, you get there only if the query returns information, that is why if it returns 1 or more rows, $i will become 1 else it will remain 0.
In your case:
$numArticles = mysql_num_rows($q);
if($numArticles > 0)
echo 'Your articles';
else
echo 'No articles :((((';
I recommend tough moving on to PDO to communicate with DB.

Categories