Not sure why this isnt working. I'm assuming it's because i am fetching an array but not sure why that would stop it.
Heres the code anyhow;
<?php
include ("../database.php");
$result = mysql_query("SELECT * FROM gigs WHERE artisturl='$artistname'");
while($row = mysql_fetch_array($result)){
if (empty($row['gigname'])){echo '<p2>'.$row['artistname']. 'has not posted any gigs yet. Check back later.</p2>';}
else {
echo $row['gigname'].$row['venue'].$row['lineup'].$row['date'].$row['time'].$row['price'].$row[' purchase'].'<br><br>';}}?>
Not sure why this isnt working
You've not stated what your criteria for 'working' are.
Your code doen't make any sense. empty() is not the right function to use here - indeed there is no function which will work here because if there are no matching records then the body of the loop will never execute.
There are lots of ways to deal with the scenario. Here's a simple one:
if (mysql_num_rows($result)) {
while($row = mysql_fetch_array($result)){
echo ....
}
} else {
echo '<p2>'.$row['artistname']. 'has not posted any gigs...'
}
Empty has unexpected results with strings, i'd suggest you read this article.
For example :
$mystring = '0';
if (empty($mystring)) {
// this code will run
// what if this was code to take action when $mystring is undefined?
}
So make sure gigname is not 0.
Consider using is_null($row['gigname']))
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.
Am getting an error of prepared statement "my_query7" already exists, i call this function each time a user tries to update table leader_info in the database, i have gone through the documentation for pg_prepare and i don't understand what is meant by it should only be run once. code snippets will be of help. Thanks.
function add_leader_country($user_id,$l_country)
{
global $connection;
$query = pg_prepare($connection,"my_query7","update leader_info set l_country = $1 where user_id = $2 and status < 9");
$result = pg_execute($connection,"my_query7",array($l_country,$user_id));
if(!$result)
{
echo pg_last_error($connection);
}
else
{
echo "Records created successfully\n";
}
$row = pg_affected_rows($result);
return $row;
}
Prepare execute does not permit duplicate naming, so that is your error.
A query should only be prepared once, for example, in a cycle for the preparation state must be set out of the for and its execution in the for.
$result=$pg_prepare($connection,"my_query7",$query);
for($id=1;$id<3;$id++){
$result=pg_execute($connection,"my_query7",array($l_country,$user_id));
...
}
In your case using a functio that use the prepare and execute multiple times it's a problem.
What are you trying to accomplish with this function dispatches more code like where you are calling the function. This way I might be able to help you.
If you want to use functions I would use this method
Exemple from https://secure.php.net
<?php
function requestToDB($connection,$request){
if(!$result=pg_query($connection,$request)){
return False;
}
$combined=array();
while ($row = pg_fetch_assoc($result)) {
$combined[]=$row;
}
return $combined;
}
?>
<?php
$conn = pg_pconnect("dbname=mydatabase");
$results=requestToDB($connect,"select * from mytable");
//You can now access a "cell" of your table like this:
$rownumber=0;
$columname="mycolumn";
$mycell=$results[$rownumber][$columname];
var_dump($mycell);
If you whant to use preaper and execute functions try to create a function that creates the preparations only once in a session. Do not forget to give different names so that the same error does not occur. I tried to find something of the genre and did not find. If you find a form presented here for others to learn. If in the meantime I find a way I present it.
require_once 'C:/wamp/www/FirstWebsite/CommonFunctions.php';
function SelectRowByIncrementFunc(){
$dbhose = DB_Connect();
$SelectRowByIncrementQuery = "SELECT * FROM trialtable2 ORDER BY ID ASC LIMIT 1";
$result = mysqli_query($dbhose, $SelectRowByIncrementQuery);
$SelectedRow = mysqli_fetch_assoc($result);
return $SelectRowByIncrementQuery;
return $SelectedRow; //HERE is the error <-------------------------------
return $result;
}
$row = $SelectedRow;
echo $row;
if ($row['Id'] === max(mysqli_fetch_assoc($Id))){
$row['Id']=$row['Id'] === min(mysqli_fetch_assoc($Id));#TODO check === operator
}
else if($row['Id']=== min(mysqli_fetch_assoc($Id))){
$row['Id']=max(mysqli_fetch_assoc($Id));#TODO check === operator //This logic is important. DONT use = 1!
Ok, I am trying to write a program for the server end of my website using PHP. Using Netbeans as my IDE of choice I have encountered an error while attempting to write a function which will store a single row in an associative array.
The issue arises when I try to return the variable $SelectedRow. It causes an 'Unreachable Statment' warning. This results in the program falling flat on its face.
I can get this code to work without being contained in a function. However, I don't really feel that that is the way to go about solving my issues while I learn to write programs.
Side Notes:
This is the first question I have posted on SO, so constructive criticism and tips are much appreciated. I am happy to post any specifications that would help an answer or anything else of the sort.
I do not believe this is a so-called 'replica' question because I have failed to find another SO question addressing the same issue in PHP as of yet.
If anybody has any suggestions about my code, in general, I'd be stoked to hear, as I have only just started this whole CS thing.
You can only return one time. Everything after the first return is unreachable.
It's not entirely clear to me what you want to return from that function, but you can only return one value.
The return command cancels the rest of the function, as once you use it, it has served its purpose.
The key to this is to put all of your information in to an array and return it at the end of the function, that way you can access all of the information.
So try changing your code to this:
require_once 'C:/wamp/www/FirstWebsite/CommonFunctions.php';
function SelectRowByIncrementFunc(){
$dbhose = DB_Connect();
$SelectRowByIncrementQuery = "SELECT * FROM trialtable2 ORDER BY ID ASC LIMIT 1";
$result = mysqli_query($dbhose, $SelectRowByIncrementQuery);
$SelectedRow = mysqli_fetch_assoc($result);
$returnArray = array();
$returnArray["SelectRowByIncrementQuery"] = $SelectRowByIncrementQuery;
$returnArray["SelectedRow"] = $SelectedRow;
$returnArray["result"] = $result;
return $returnArray;
}
And then you can access the information like so:
$selectedArray = SelectRowByIncrementFunc();
$row = $selectedArray["SelectedRow"]
And so forth...
UPDATE: I solved it using a for loop:
for ($i=0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);
echo $row['name'];
}
ORIGINAL QUESTION:
This looks kinda stupid. I'm sure im missing something that's very simple, since I was able to accomplish this before. Anyways, I want to echo some text for every item in an array. This array is derived from mySQL.
here's the code
while ($row = mysql_fetch_assoc(mysql_query("SELECT * FROM files"))) {
echo $row['name'];
}
can you post the complete code? I think you forgot the database connection.
Try this:
$result = mysql_query("SELECT * FROM files") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
var_dump($row['name']);
}
This will throw an error, I guess you made a mistake over there. Also, var_dump() your $row in the while to make 100% sure you have "a" value.
Also, are you sure the row does exist? If don't have any records, the echo on your $row will not work sinc it does not exist.
Also, set error reporting to E_ALL like so.
error_reporting(E_ALL);
Also, since you are running your query inside the while() loop, it will continue to run forever. So first run the query, and put it in a variable, and then loop through the results. (see my piece of code above)
You can execute query individual instead of while loop because if your query return more than 1 rows it will goes under the loop. show your loop print only first data of result and your loop is infinite.
From your question it seems so simple, try this way it's working.
$sql="SELECT name From files";
$names = $db->query($sql);
while($name1 = $db->fetchByAssoc($names))
{
echo $name1['name'];
}
I have the following problem:
public function row2Partner($row){
echo $row->PartnerID;
}
public function main(){
$query = "SELECT PartnerID, PartnerName FROM Partner";
$result = mysql_query($query);
$this->row2Partner(mysql_fetch_object($result));
}
This gives me the error in row2Partner():
Trying to get property of non-object
But $row is an Object! And if I do
echo $row->PartnerID in the main function, it works.
Any ideas?
Thx,
Martin
If your result returns more than one row, your object is going to be multi-dimensional. I'm pretty sure you can do something like this if you just want to echo the first one:
public function row2Partner($row){ echo $row[0]->PartnerID; }
If you are looking for only one result, I would also limit my query to just one...
SELECT PartnerID, PartnerName FROM Partner LIMIT 1
If you want to echo out all your rows (in the case of multiple) results, you can do this:
public function row2Partner($row){
foreach($row as $result) {
echo $result->PartnerID;
}
}
Hope that helps.
PS
Just as a sidenote, I tend to like to use associative arrays when dealing with MySQL results--it just makes more sense to me. In this case, you would just do this instead:
mysql_fetch_assoc($result)
Are you sure that mysql_query() has executed the query successfully, and also that there is actually a row being returned? It might be worth checking it, e.g.
//check query executed ok
if ($result = mysql_query($query)) {
//check there is actually a row
if ($row = mysql_fetch_object($result)) {
$this->row2Partner($row);
} else {
//no data
}
} else {
//error
die(mysql_error());
}
Best thing I can think of is that you may need to pass by reference rather than by value. Change your function declaration to
public function row2Partner(&$row)
Hope that helps,
David