In this script, I basically want to echo out data from a mysql table when the certain row record matches the name in browser address bar. But for some reason, no data is echoed. Any reason my while loop doesn't work?
$users = $_GET['username'];
$other_friend_query = mysql_query("SELECT * FROM friend WHERE RelatingUser='$users'");
$other_friend_assoc = mysql_fetch_assoc($other_friend_query);
while ($other_friend_assoc = mysql_fetch_assoc($other_friend_query)) {
$friend_related = $other_friend_assoc['RelatedUser'];
echo $friend_related;
}
That's because you call mysql_fetch_assoc before your while loop. When you call this, it fetches a result. Then when you go to your loop, that result has already been fetched. Just remove that and you'll be good to go. As stated in the comments, stop using mysql_ functions. The code below will escape your posted variable and also check for errors. It's also better practice to use a column list, instead of SELECT *.
$users = mysql_real_escape_string($_GET['username']);
$other_friend_query = mysql_query("SELECT * FROM friend WHERE RelatingUser='$users'") or die( mysql_error() );
while( $other_friend_assoc = mysql_fetch_assoc($other_friend_query) ) {
$friend_related = $other_friend_assoc['RelatedUser'];
echo $friend_related;
}
Any reason my while loop doesn't work?
May not be the only reason, but you're skipping the first result.
// the following line is unused and therefore unnecessary
$other_friend_assoc = mysql_fetch_assoc($other_friend_query);
while ($other_friend_assoc = mysql_fetch_assoc($other_friend_query)) {
Related
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.
$sqlWork = "SELECT * FROM work WHERE user_id = '$_SESSION[user_id]'";
$resultWork = $connection->query($sqlWork);
$rowWork = $resultWork->fetch_assoc();
I currently have this table.
(I would add an image if I had the reputation)
http://imgur.com/fEYrzY0
This is how I am outputting my data.
do {
echo "{$rowWork['work']}";
} while ($description = mysqli_fetch_array($resultWork));
use:
while($rowWork = $resultWork->fetch_assoc()){
echo $rowWork['work'];
}
I see that you are not using parametrized query, your code is vulnerable to SQL injection attack, you can avoid it by using prepared statement (parametrized)
$sqlWork = "SELECT * FROM work WHERE user_id = '$_SESSION[user_id]'";
$resultWork = $connection->query($sqlWork);
while ($description = mysqli_fetch_array($resultWork)){
echo $description['work'];
}
You can also do this based on these:
foreach
Use when iterating through an array whose length is (or can be) unknown.
for
Use when iterating through an array whose length is set, or, when you need a counter.
while
Use when you're iterating through an array with the express purpose of finding, or triggering a certain flag.
I have a problem. I have an array of values from database, when I try to pass it to a string with commas, it works fine on my localhost, but when I upload it to my online server, the string doesn't show any values. For example: select from table where in (,,) only shows the commas and in my xampp server it works excellent. Any ideas what this can be?
Here's the code:
<?php
$sql = "select id from users where gid = 1";
$result = mysql_query( $sql);
$cat_titles=array();
while( $row=mysql_fetch_assoc($result) )
{
$cat_titles[] = $row['id '];
// do stuff with other column
// data if we want
}
mysql_free_result( $result );
echo "<p>\n";
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
echo "</p>\n";
$cat_titles = implode(',',$cat_titles);
$cat_titles = substr($cat_titles,0,-2);
echo $cat_titles;
echo "select * from users where IN (".$cat_titles.")";
?>
A number of potential issues here:
You are not handling error conditions around you database access, so if you are having issue with your queries you would never know.
Your second select query doesn't specify a field in the WHERE clause, so it will never work
This section of code does absolutely nothing and is in fact where you problem likely lies.
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
Here $row['id'] won't have a value, so you are basically looping throguh your existing array and appending empty value to new indexes.
In all likelihood you could do this with a single query, it might help if you explain what you are actually trying to do.
You should not be using mysql_* functions. They are deprecated. Use mysqli or PDO instead.
hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>
I have a query that returns a few rows, and I have the following lines of code to retrieve them:
$result_set = mysql_query($query);
while($net_biz_sub_data[]=
mysql_fetch_array($result_set,MYSQL_ASSOC));
My question is what is the right way to retrieve that db query data without getting the last array empty ?
When I count() it is always num of rows + 1, and I would like to correct that.
Because of the way the while loop works, you should do
while($dataz = mysql_fetch_assoc($result_set))
{
$net_biz_sub_data[] = $dataz;
}
Use
$result_set = mysql_query($query);
while($net_biz_sub_data = mysql_fetch_assoc($result_set)){
//use $net_biz_sub_data here
}