I'm working on a piece of code that's meant to be implemented in Google Charts, however, not all values I'm looking for are being returned.
I need a couple of dates selected from my database, and I select them as follows:
$dates = mysql_fetch_row(mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'")) or die(mysql_error());
Then I use a for-loop to echo them:
for ($i = 0; $i <= count($dates); $i++)
{
echo $dates[0].' ';
}
In my database there are 3 (distinct) dates: 24-03-2013, 25-03-2013 and 26-03-2013, however the piece of code returns 2x 24-03-2013. What am I doing wrong here?
P.S. I also tried a while-loop but that loops infinitely or crashes my page. Besides that, I tested the query by running it in the database itself and it returns the right results, so the query works fine.
Help is much appreciated!
You need to use mysql_fetch_row() inside a loop in itself:
$result = mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'");
while($date = mysql_fetch_row($result))
{
echo $date[0];
}
You should also note that the mysql_* family of functions are not deprecated. You should avoid using them if possible, and look into alternatives such as MySQLi or PDO.
Try this: mysql_fetch_row() fetches only one row, If you need all the rows use mysql_fetch_assoc()
$sql = mysql_query("SELECT DISTINCT date FROM participants WHERE subdomein='testdomain'");
while($dates = mysql_fetch_assoc() ($sql)){
print_r($dates);
}
Ref: http://php.net/manual/en/function.mysql-fetch-row.php
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
mysql_fetch_row only returns one record from the actual result of your query. You have to call it several times, ontil it returns null :
$res = mysql_query(...);
while (($record = mysql_fecth_row($res)) !== null) {
print_r($record[0]);
}
Please note mysql_* function are deprecated and should not be used anymore, too.
Related
I am very new to PHP and I realise I have a lot to learn, especially about SQL injection attacks and the new php 5.5 oo stuff.
However, whilst I am learning I try to play about a bit and experiment and I have come across a problem. I need to get all results from one column (team_name) of my query into an array (zero indexed would be easier) so that I can put those results into a foreach loop to create a fixture list. For example - this is what I would like to do with the data...
foreach ($teams as $team) {
foreach ($teams as $opposition) {
if ($team != $opposition) {
echo "$team versus $opposition";
}
}
}
So my sql query is as follows...
$query="select * from pool_a";
$result=mysql_query($query);
$num=mysql_num_rows($result);
Then I can easily output the data I am looking for as follows;
echo "<table>";
for ($i=0;$i<$num;$i++) {
$teams=mysql_result($result,$i,'team_name');
echo "<tr><td>$teams</tr>";
}
echo "</table>";
But what I can't do is get the data into an array. I thought that data that came back from a msql_query such as the above always came back as an array, no matter the number of results, but if I run an is_array() check on $teams, it returns false.
I have tried using explode (after adding a comma after each team name and trimming the last one off) and then using a foreach loop but it only ever returns the value associated with the index [0]. I should add here that although the key is 0, the actual value I get is the LAST in the list when echoed as above, which I also don't understand.
Any help would be much appreciated.
Thanks
$team_names = array();
while ($row = mysql_fetch_assoc($result)) {
$team_names[] = $row['team_name'];
}
mysql_fetch_assoc, mysql_fetch_row, and mysql_fetch_array all return a row as an array (they differ in how it's indexed). But mysql_result just returns a single item from the result, so it doesn't return an array.
You could do the same thing as above with your use of mysql_result, but you still have to push them onto the result array yourself:
for ($i=0;$i<$num;$i++) {
$team=mysql_result($result,$i,'team_name');
$team_names[] = $team;
}
To get the results of the query into an array, you can do this
$query="select * from pool_a";
$result=mysql_query($query);
$result_arr = mysql_fetch_array($result);
$num=mysql_num_rows($result);
However, consider using the PDO drivers to connect to the database. It's far superior to doing it procedurally, and it's safer as Prepared Statments will help protect you against injection attacks. The method you're using is deprecated.
Instead of using mysql_result try using mysql_fetch_array($result, MYSQL_ASSOC)
This function will give you an array of whatever your result from MySQL is.
I know this is something simple. I'm just forgetting something.
I'm counting the values of the rows in the "numberattending" column of my database.
When I run the SQL statement
SELECT COUNT(numberattending) AS Total FROM RSVP
in the mySQL window I get the total I'm looking for.
When I try to extract that value and echo "num_seats" I get "Resource id #3"
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
echo $num_seats;
What I'm I missing?
Thanks for any help ahead of time.
$num_seats represents a MySQL Resource, not the value of the field selected. You'll need to use either mysql_fetch_array() or mysql_fetch_object() depending on which you prefer.
For example:
$number = mysql_fetch_array($num_seats);
echo $number['Total'];
It's also worth noting that the mysql_* family of functions are now deprecated, and you should really be using MySQLi or PDO.
You need to loop through the result sets:
From the PHP site:
// Use result // Attempting to print $result won't allow access to
information in the resource // One of the mysql result functions must
be used // See also mysql_result(), mysql_fetch_array(),
mysql_fetch_row(), etc.
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
while ($row = mysql_fetch_assoc($num_seats )) {
echo $row['total'];
}
PS: As others will surely tell you, use of the mysql* functions have been deprecated. Look for the mysqli functions instead.
Try
$query = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
$result = mysql_fetch_row($query);
echo $result['Total'];
Google hasn't been much help sadly. I have some pseudo code below to give you an idea of what I'd like to achieve:
if ($time == one week) {
$result = mysql_query("SELECT * FROM table RANDOMLY,$connection");
echo $result[0];
}
I know I should be using mysqli, but I'm augumenting an existing (ageing) system. I'll be utilising mysqli in future, so if you could give me the solution using mysql that would be great!
I don't think it can be done with a single statement.
My best guess would be to use mysql_list_tables, select a random entry from that list and continue from there on.
Perhaps generating a random number between 1 and the value of SELECT Count(ID) from table. Then you have the index of the value you wish to output, you can simply run a SELECT statement for it; and output! :)
if ($time == one week) {
$result = mysql_query("SELECT * FROM table RANDOMLY,$connection");
echo $result[0];
}
Try this:
$weekNumber = date("W");
$result = mysqli_query("SELECT * FROM table RANDOMLY WHERE weeknumber = '\"$weekNumber\"', $connection");
echo $result[0];
}
Of course you’ll need a column in your table called weeknumber with 1 through 52 setup ahead of time.
As others pointed out you shouldn’t use mysql_* anything. I changed it to a mysqli_query.
I'm selecting a single column from a MySQL table with mysql_query(). Is there already a function for getting the results into an array, or will I have to iterate through all the results with something like mysql_fetch_array()?
You have to iterate.
If you moved into the 21st century, and used mysqli, there's a mysqli_fetch_all() function.... and you'd be able to use prepared statements
you can do this with mysqli_fetch_all and array_column
$r = mysqli_query($c,"SELECT bug_name FROM bugs WHERE color='red'");
$bug_names = array_column(mysqli_fetch_all($r,MYSQLI_ASSOC),"bug_name");
Nothing like that built in, you will need to do this manually.
you can use mysql_result function still need to do some coding
mysql_result($result,$row_num,$fieldname) ;
retrieves $row_num 'th columes $field_name field .
and following snippet can be taken as an example
$con =mysql_connect($host,$uname,$passwd);
mysql_select_db($dbname,$con);
$result = mysql_query($query,$con);
$arr = array();
$numrows = mysql_num_rows($result);
for($i=0;$i<$numrows;$i++) {
$arr[] = mysql_result($result,$i,$fieldname);
}
this stores every elements of column $fieldname to
array $arr
I am having great trouble trying to use mysql_fetch_assoc and mysql_result together in the same PHP script.
Originally (when not utilizing the mysql_result function) I was getting the required database values using a combination of mysql_query and mysql_fetch_assoc and everything was fine. Then i added 2 lines into my code to obtain certain ‘title’ field values using mysql_result.
Now if i run my script as it is below i will only receive 1 result even though there are 2 result. Then if i move my do/while loop up so that it is between the other 2 blocks of code (mysql_fetch_assoc and mysql_result lines) i will receive the desired 2 results.
I need my loop to come after the mysql_result section so putting the loop before it is not an option.
// connect to DB and get values
mysql_select_db($database, $mywebsite);
$query_not_related_before = "SELECT * FROM table limit 2";
$not_related_before = mysql_query($query_not_related_before, $ mywebsite);
$row_not_related_before = mysql_fetch_assoc($not_related_before);
// Extract just the results from the title field (the problem area!)
$before_essayid4 = mysql_result($not_related_before,0, 'title');
$before_essayid5 = mysql_result($not_related_before,1, 'title');
// Display results etc
do {
echo "<br />".$row_not_related_before['title']."<br />";}
while ($row_not_related_before = mysql_fetch_assoc($not_related_before));
Plase help,
Many thanks,
David
I am unsure if this will solve your problem but I think you should "seek" the result back.
mysql_data_seek ($not_related_before, 0)
Also, check out the warning on the mysql_result page:
Calls to mysql_result() should not be
mixed with calls to other functions
that deal with the result set.
Hope this helps ;)
You get one row because the first already requested here:
$row_not_related_before = mysql_fetch_assoc($not_related_before);
So I think you have to move result pointer to beginning:
mysql_data_seek($not_related_before, 0);
// Display results etc
do {
echo "<br />".$row_not_related_before['title']."<br />";}
while ($row_not_related_before = mysql_fetch_assoc($not_related_before));
A simpler solution would be to use 2D array's, i have always found the mysql functions to be a little cumbersome.
<?php
$result = mysqli_query(db_connect(),$query);
$result_out = array();
if(#mysqli_num_rows($result))
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))$result_out[]=$row;
foreach($result_out as $row)
{
echo "<br />".$row['title']."<br />";
}
?>
hth