my xampp localhost was working well till i add this code to my php file
<?php while ($notification) {?>
<li>
<?php
echo $notification['notification'];
?>
</li>
<?php
} ?>
now the page is not loading or partially loading
here $notification is
$notification_sql= "SELECT id FROM notifications WHERE user_id='{$_SESSION['user']}'";
$notification_query = mysqli_query($conn, $notification_sql);
$notification = mysqli_fetch_assoc($notification_query);
Before I begin I want to recommend you something: Avoid the use of the while statetements. Unless they are really needed - like in the exact way they are used in the PHP docs (and even then you can find alternatives) - they should be avoided all the time. I present the motive down under.
That said,... it's not $notification['notification'], but $notification['id'].
After you change it, you still remain with the issue: an infinite loop. Because you are using a while loop without changing the state of the loop condition. E.g_ you are validating the $notification array for beeing existent. Because it exists all the time - it's state never beeing changed in the loop - then the iterations will be infinite in number. In order to avoid this dangerous (!!!) situation, you can use the following codes.
Method 1:
Notice the difference: $notification is valid only for the period of a loop step. After each iteration $notification is newly created. And, when mysqli_fetch_assoc() returns FALSE on the (last + 1)-iteration step, then the $notification receives that value and, therefore, the loop ends.
<?php
$notification_sql = "SELECT id FROM notifications WHERE user_id='{$_SESSION['user']}'";
$notification_query = mysqli_query($conn, $notification_sql);
if ($notification_query) {
while ($notification = mysqli_fetch_assoc($notification_query)) {
?>
<li>
<?php
echo $notification['id'];
?>
</li>
<?php
}
mysqli_free_result($notification_query);
}
?>
Method 2:
Or, if you want to fetch the results in an array and to output its items later, then you can do it like this:
<?php
$notification_sql = "SELECT id FROM notifications WHERE user_id='{$_SESSION['user']}'";
$notification_query = mysqli_query($conn, $notification_sql);
$notifications = array();
if ($notification_query) {
while ($row = mysqli_fetch_assoc($notification_query)) {
$notifications[] = $row['id'];
}
mysqli_free_result($notification_query);
}
// OTHER STUFF AFTER FETCHING...
?>
<?php
// LOOPING AT A LATER TIME.
foreach ($notifications as $notificationId) {
?>
<li>
<?php
echo $notificationId;
?>
</li>
<?php
}
?>
Other recommendations:
Use prepared statements in order to avoid MySQL injection.
Use exception handling in order to catch all errors and handle them correspondingly. Especially when you run database operations.
Use PDO instead of mysqli.
Here I have provided full code examples of prepared statements combined with exception handling (using mysqli library):
Can't insert info in a server, but i can as localhost (See EDIT 2)
Login using MySqli Prepared Statement (See solution 1 & 2)
Good luck.
Related
I have issues with category and subcategory fields.
shortly, I made category like this: literature, and want to make drop down sub menu like this: poetry, novel, non-fiction.
I receive all the categories on the website, but can't get subcategory field at all.
Here is my code:
$category=htmlspecialchars($_REQUEST['category']);
if(isset($category)){
$avt=mysql_query("select * from category order by id asc");
while($category_id=mysql_fetch_array($avt))
{
?>
<li><a href="#"> <k style="font-size:11px;"> <?
echo $category_id['catname'];
} }
?> </k> </a>
<?
$subcategory=htmlspecialchars($_REQUEST['subcategory']);
if(isset($subcategory)){
$sql = mysql_query("SELECT t1.*,t2.* FROM category as t1, subcategory as t2 WHERE t1.id=t2.'$_REQUEST[subcat_id]'");
while($data = mysql_fetch_array($sql))
{ ?>
<ul style="z-index:101;">
<li> <k> <?php echo $data["subcat_name"]; ?> </k></li>
<? } }
?>
And here is the mysql:
category
id
catname
Subcategory
id
subcat_id
subcat_name
That's all. I would be grateful if some can help me to solve this. (I am beginner obviously)
Thank you
Even though you are a beginner, I would suggest you probably heavily retool this. Start with your database connection. mysql_ functions are deprecated (not recommended for use) in the latest v5 of PHP and removed altogether in PHP v7 because they are security risk and are poorly implemented by most. Use PDO or MySQLi instead. I prefer PDO, so I will demonstrate that:
# Create the connection thusly, fill in your own credentials
$con = new \PDO("mysql:host=localhost;dbname=mydatabase", $username, $password);
Next, you should know the difference between isset and empty. In your case, your isset will throw a warning if $_REQUEST['category'] is not set. When you create your own variable, it's guaranteed to be set when you check it because you manually just created it.
This will throw a warning if $_REQUEST['category'] is not set because you assign it before you check it:
$category = htmlspecialchars($_REQUEST['category']);
This WILL NOT throw a warning because you are checking if $_REQUEST['category'] is set yet. If not, assign $category to false by default:
# I like to use a ternary when there are only two options, but you can use if/else
$category = (isset($_REQUEST['category']))? htmlspecialchars(trim($_REQUEST['category'])) : false;
# This part now checks if the value that you created is NOT EMPTY because you
# have just created it, so checking if it is set is illogical
if(!empty($category)):
# Now we use our connection here to query.
# Here we can use query() because we don't have any variables to add into the query,
# so it's safe to use this short version
$avt = $con->query("select * from category order by id asc");
# Same while loop, just use the PDO version of fetching the results
while($category_id = $avt->fetch(\PDO::FETCH_ASSOC)): ?>
<?php
/**
* I'm not sure why you are using a "k" tag, so just combine with "a" tag
* also, though you can use <? as a php open, it's not recommended
* lastly, you have the close tag for "a" outside the loop, that is bad syntax
* since the open is inside the loop
*/
?>
<li><?php echo $category_id['catname'] ?></li>
<?php endwhile ?>
<?php endif ?>
Now that the top part is finished, you have the same issues (plus a couple more) on this second part of the code:
# It's also worth noting here you have set this variable, but you don't actually use it...?
# Secondly, you are checking for "subcategory" here, but in the code below you are injecting "subcat_id"...should they match??
$subcategory = (isset($_REQUEST['subcategory']))? htmlspecialchars(trim($_REQUEST['subcategory'])) : false;
if(!empty($subcategory)):
# Here is where you need to make a detour with your script. What you are doing is unsafe.
# You can not inject that value right into the sql. You need to "prepare", "bind value", and "execute" it
$subcat_id = $_REQUEST['subcat_id'];
# First prepare using ? as placeholders for the value you want to search for
# The naming convention on the "subcat_id" column I assume is actually the
# the parent category? If so, maybe it should be called "parent_id" or "category_id"??
$sql = $con->prepare("SELECT t1.*, t2.* FROM category as t1, subcategory as t2 WHERE t1.id = ? AND t2.subcat_id = ?");
# Now you want to execute for those two question marks (?)
# There are a few ways to prepare and bind parameters, this way is easy
# and you can visually see what we are trying to accomplish
$sql->execute([$subcat_id, $subcat_id]) ?>
<!-- you probably don't want to be looping this (or it's close tag) -->
<ul style="z-index:101;">
<?php
# Same type of thing as your first block of code
while($data = $sql->fetch(\PDO::FETCH_ASSOC)): ?>
<li> <?php echo $data["subcat_name"] ?> </li>
<?php endwhile ?>
<!-- end list -->
</ul>
<?php endif ?>
The final conclusion here is that you have some work to be done before you get to the main problem which is likely your SQL statement and the value you are querying. I would suggest reading up on any of the concepts mentioned that you are not familiar with.
I'm updating some old code that has deprecated MySQL functions. But for some reasons I cannot get all the results from the column. The strange part is that if I run the query directly on the server I get all results fine. So this is an issue with PHP getting the results, not the MySQL server or my query.
Here is the new and old code:
My current updated code:
$sql = "SELECT user, monitor FROM users WHERE `status` = 'y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// This works. It shows all results
echo $row["user"];
// This does not work! Only shows one result:
$account= $row["user"];
}
else {
echo 'No results';
}
When I use that query directly on DB server, I get all results. So the SQL query is correct. I actually also get all results as well in PHP if I echo the row directly like:
echo $row["user"];
But for some reason when I try to use it with a PHP with variable it only lists one user result.
In the past I used this but the mysql_fetch_array function is now deprecated
while ($row = mysql_fetch_array($result)) {
array_push($data, $row["user"]);
}
foreach($data as $value) {
$account = $value
}
I cannot use my previous code anymore as those MySQL functions are obsolete today. I need to write the results into a file and my old method worked fine. The new one using mysqli does not.
Any suggestions?
You just need to add one of these [, and one of these ].
$account[] = $row["user"];
// ^^ right here.
$account= $row["user"]; means you're storing the value of $row["user"] in $account each time the loop executes. $account is a string, and it gets a new value each time.
$account[] = $row["user"]; means you're appending each value of $row["user"] to an array instead.
You should not use array_push for this. It's overkill for appending a single value to an array. And if the array isn't defined beforehand, it won't work at all.
I am using MySQLi multi_query to work with several select statemets at a time.
What i would like to know is how to handle results, so i will be able to use them later in code.
Example:
<?php
//connection stuff
$query = "SELECT name, surname FROM database1;";
$query.= "SELECT car, year, type FROM database2 WHERE carID='1';";
$query.= "SELECT product, price FROM database3;";
if ($mysqli->multi_query($query)) {
if($result = $mysqli->store_result()) {
while($row = $result->fetch_row()) {
--> what to do here?
}
}
}
?>
<html>
<div id='persona'>
<?php
foreach() {
--> print name + surname
}
?>
</div>
<div id='cars'>
<?php
foreach() {
--> print car + year + type
}
?>
</div>
<div id='product'>
<?php
foreach() {
--> print product + price
}
?>
</div>
</html>
One more thing, prepared statements are not possible when using multiple_query, right?
There really is no benefit in putting unrelated queries together in one multi query call. In fact, the risk of getting hit by a SQL injection is way bigger! The regular query function does only allow one query per call, so it is impossible to inject something into a SELECT statement, ending it prematurely and then add a DELETE.
With multi_query, this is possible.
Additionally, you have to fetch and end each query, and then it's gone. You you cannot change between the query results at will, they have to be fetched in exactly the order they were issued.
The better way is to just execute independent simple queries. This would allow you to use prepared statements as well, and as long as you are not getting HUGE amounts of data back, it will probably use the same amount of memory and not annoy anyone.
I'm currently pulling the data from MySQL Database with the current code Example 1
function User_Details($uid){
$uid = mysql_real_escape_string($uid);
$query = mysql_query("SELECT uid,password,email,nickname,username,profile_pic,friend_count FROM users WHERE uid='$uid' AND status='1'");
$data = mysql_fetch_array($query);
return $data;
}
I'd like to use this query across multiple PHP pages without having to write a foreach loop for every PHP file.
Currently I have it inside a class called class Wall_Updates { }, and I try to print it with the following code: Example1 : < ?php echo $data['username']; ? >.
The class Wall_Updates is being called on the header which should also include the User_Details, so the only issue is how do I print with just the following PHP example I gave above without the need of a loop.
The class words with single fielded queries such as Example 2 $face = $Wall->Profile_Pic($msg_uid); and if I echo $face it'll show my current Profile_Pic which is a single query.
Example 3 of how I don't want to do as it's very messy.
<?php
if ($uid) {
$updatesarray = $Wall->Updates($uid);
}
if ($updatesarray) {
foreach ($updatesarray as $data) {
$username = $data['username'];
?>
#HTML CODE GOES HERE
<?php } ?>
So I'd like my query to pull multiple fields from users and use it across any page without a foreach.
PS: I'm sorry if it's not making sense, I've been complained a lot for not showing what I've tried and I hope to not get complained about it this time, I appreciate for looking at my question.
you need to issue the "or die" sql command EVERYWHERE otherwise you have no idea why it failed.
http://pastie.org/7897405
you have a column name wrong (look at the last line of the pastie
also, get off of the mysql_ stuff and get into pdo. you should know better chump !
I have a header.php and a footer.php file being included on the same page, they both return some of the same information. Specifically I use this query in each file.
<?php
$q3 = "SELECT page_id, show_id, link_title FROM pages as p WHERE show_id = 1";
$r3 = #mysqli_query ($dbc, $q3); // Run the Query.
while ($nav = mysqli_fetch_array($r3, MYSQLI_ASSOC)) {
echo"<li>{$nav['link_title']}</li>"
}
?>
This is to show the pages in both the header and footer.
However SOMETIMES the second query in the footer returns a "Couldn't fetch mysqli", sometimes it works, sometimes it doesn't. I was wondering should I be using something like mysqli_free_result() would that be better practice?
Even more, is it good practice to free the result after every query? Is there a better way to use the same result from different pages and <?php // ?> tags?
Also, I get the error "too many mysql connections error" every now and then? Is this because I am not closing connections after queries are ran?
You could begin with removing the # from your code. Error suppression is slow and harmful practice.
If you inlcude's are in same scope, you can just save the value of first in some variable, and check in second , if variable has been set.
content of header.php
$storage = '';
$query = "SELECT page_id, show_id, link_title FROM pages as p WHERE show_id = 1";
if ( $result = mysqli_query ($dbc, $query))
{
while ($nav = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$item = "<li>{$nav['link_title']}</li>";
$storage .= $item;
echo $item;
}
}
else
{
echo 'Query has failed !';
}
content of footer.php
if ( isset( $storage ) && count( $storage ))
{
echo $storage;
}
else
{
echo 'Query has failed !';
}
Read about include() in the fine manual.
And please , stop writing that this procedural perversion. Learn how to do OOP and read about PDO.
Run the query only once, prior to including the header and footer and store the results in a variable - you can use them as many times as you want after that.
mysqli_free_result() should be used only if you have a really large result set, as PHP would take care of free-ing it after it's no longer needed and manually doing this every time just creates extra overhead.
You are getting the "too many connections" error because you're probably opening multiple connections as you do with repeating the same query - create just one before including any other script and just reuse it. You should use the standard mysql extension with mysql_pconnect() for an even better solution to this one ... otherwise - yes, close the connection after you no longer need it.