Fetching data from database, not getting correct data - php

I have a database which looks like so -
I am trying to fetch the top 10 entries based on time (entries with top 10 values in time column). I have the following code.
<?php
include_once("connect.php");
$sql = "SELECT * FROM scores order by time desc limit 10";
$query = mysql_query($sql) or die("systemResult=Error");
$counter = mysql_num_rows($query);
if($counter>0)
{
print("systemResult=Success");
$array = mysql_fetch_array($query);
foreach($array as $data)
{
$athleteName = $data["athleteName"];
$email = $data["email"];
$time = $data["time"];
$timeStamp = $data["timeStamp"];
$country = $data["country"];
print "&athleteName=" . $athleteName;
print "&email=" . $email;
print "&time=".$time;
print "&timeStamp=".$timeStamp;
print "&country=".$country;
}
}
else
{
print("systemResult=Error");
}
?>
The output I am getting is
systemResult=Success&athleteName=7&email=7&time=7&timeStamp=7&country=7&athleteName=7&email=7&time=7&timeStamp=7&country=7&athleteName=4&email=4&time=4&timeStamp=4&country=4&athleteName=4&email=4&time=4&timeStamp=4&country=4&athleteName=G&email=G&time=G&timeStamp=G&country=G&athleteName=G&email=G&time=G&timeStamp=G&country=G&athleteName=n&email=n&time=n&timeStamp=n&country=n&athleteName=n&email=n&time=n&timeStamp=n&country=n&athleteName=2&email=2&time=2&timeStamp=2&country=2&athleteName=2&email=2&time=2&timeStamp=2&country=2&athleteName=I&email=I&time=I&timeStamp=I&country=I&athleteName=I&email=I&time=I&timeStamp=I&country=I
As can be seen, the output I am getting is not what is on the table in database. I am getting wierd values. What am I doing wrong?

You don't need to use for each in your case, and if so, just print $data, try to remove foreach loop, and if you want to get all records, then, use while:
while($data = mysql_fetch_array($query))
{
$athleteName = $data["athleteName"];
$email = $data["email"];
$time = $data["time"];
$timeStamp = $data["timeStamp"];
$country = $data["country"];
print "&athleteName=" . $athleteName;
print "&email=" . $email;
print "&time=".$time;
print "&timeStamp=".$timeStamp;
print "&country=".$country;
}

try
while($data = mysql_fetch_array($query)) {
$athleteName = $data["athleteName"];
//...

Related

Stored Procedures PHP

My Stored Procedure only works on the first iteration. My code:
// Display Event
$result = mysql_query("select ....",$connection_mercury);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$provider = $row['name'];
$details = mysql_query("CALL $my_schema_to_use.getRefId($provider);",$connection);
while($b_row = mysql_fetch_array($details))
{
$details_result = $b_row['age'] . " - " . $b_row['address'];
}
echo "<td>$details_result</td><td>$id</td>
}
Lets say the outer while loop does 2 loops as expected. But the 'CALL' only returns a value on the first loop every time. The $details variable always remains empty for any loop after the first one.
$details_result varible are overwritting with inner loop.
while($b_row = mysql_fetch_array($details))
{
$details_result = $b_row['age'] . " - " . $b_row['address'];
}
Code should be
while($b_row = mysql_fetch_array($details))
{
$details_result[] = $b_row['age'] . " - " . $b_row['address'];
}

Multiple database row values in single variable

I am adding all names in to single variable but it is showing only one value last one.
my code is:
include 'dbconnect.php';
$result = mysql_query("SELECT * FROM bookedtates WHERE SID='$ServiceHosterIdv' AND BOOKEDDATE='$q'");
//$result = mysql_query("SELECT * FROM bookedtates WHERE SID='$ServiceHosterIdv' AND BOOKEDDATE='$q'");
while ($row = mysql_fetch_assoc($query)) {
$csk = "'".$row['NAME']."',";
}
echo $csk;
No u just assign variable use it to plus add a "." before equtaion
$csk .= "'".$row['NAME']."',";
But I would suggest to use array so u can use for JS(if ajax) or php for more flexible things
$csk = array();
while ($row = mysql_fetch_assoc($query)) {
$csk[] = array($row['NAME']);
}
echo $csk; //for ajax use echo json_encode($csk);
just test with
include 'dbconnect.php';
$result = mysql_query("SELECT * FROM bookedtates WHERE SID='$ServiceHosterIdv' AND BOOKEDDATE='$q'");
//$result = mysql_query("SELECT * FROM bookedtates WHERE SID='$ServiceHosterIdv' AND BOOKEDDATE='$q'");
$csk = '';
while ($row = mysql_fetch_assoc($query)) {
$csk .= "'".$row['NAME']."',";
}
echo $csk;
You are resetting the variable to the value of $row['NAME'] on each iteration of the loop.
What you need to do is append the variable to the end of $csk:
$csk .= "'".$row['NAME']."',";
^---- notice the extra . here
The extra . indicates that you want to append the value to $csk.

Getting newest message from user

How can I get the newest message from the person who sends a user a message?
Right now it's showing...
first_name last_name This is the newest message I sent you 2012-08-11 14:23:38
first_name last_name test 2012-08-11 14:20:35
<?php
echo '<div id ="inbox_name">Name</div><div id="inbox_message">Message</div><div id="inbox_time">Time</div><div id="inbox_line"></div>';
$query = mysql_query("SELECT * FROM `private_messages` WHERE `to_id`=$session_user_id ORDER BY `time_sent` DESC") or die("Error connecting to database. Please try again later.");
while ($row = mysql_fetch_array($query)) {
$to_id = $row['to_id'];
$from_id = $row['from_id'];
$message = $row['message'];
$time= $row['time_sent'];
$message_information = mysql_query("SELECT * FROM `sentrl_users` WHERE `id`=$from_id LIMIT 1");
while ($row_information = mysql_fetch_array($message_information)) {
$first_name = $row_information['first_name'];
$last_name = $row_information['last_name'];
$username = $row_information['username'];
echo '<div id="inbox_information"><div id="recieved_name">'. $first_name . ' ' . $last_name .'</div><div id="recieved_message">'. $message .'</div><div id="recieved_time">'. $time .'</div></div>';
}
}
?>
I tried using limit 1, but that didnt work. I'm trying to just get the newest message WITHOUT duplicating the first_name and last_name.
If what you want is ONLY ONE row, instead of
while ($row = mysql_fetch_array($query)) {
//EVERYTHING INSIDE THE ORIGINAL WHILE LOOP
}
you should write
while($row=mysql_fetch_array($query)){
$array[$row["from_id"]]=$row;
}
foreach($array as $row){
//EVERYTHING INSIDE THE ORIGINAL WHILE LOOP
}

Store Column Values in Array

I'm trying to store the title(summary) and date(created) of an event in an array. But I think im missing something in my loop.
<?php
$summary = array();
$date = array();
mysql_connect('mysql.server', 'myUsername', 'myPass') or die('Could not connect: ' . mysql_error());
mysql_select_db("mxgsite") or die(mysql_error());
$query_summary = mysql_query('SELECT summary FROM event_info') or die(mysql_error());
$query_date = mysql_query('SELECT created FROM event_details') or die(mysql_error());
$row_summary = mysql_fetch_array($query_summary);
$row_date = mysql_fetch_array($query_date);
$i = 0;
while(($row1 = mysql_fetch_array($query_summary))) {
$row2 = mysql_fetch_array($query_date);
$summary[] = $row['summary'];
$date[] = $row['created'];
echo $summary[$i] . " " . $date[$i] . "<br ?>";
$i++;
}
I know i'm getting values because I can echo out 1 value, but if I want to put all the values in an array and try to echo out that array I keep getting blank values?
It seems to me like you are trying to do too many things here. Since the 2 sets of values are not being stored in a way where they are related/linked to each other, you might as well deal with them in separate while loops. Try something like this:
while ($row = mysql_fetch_array($query_summary)){
$summary[] = $row[0];
}
while ($row = mysql_fetch_array($query_date)){
$date[] = $row[0];
}
If you want to relate the tables, per the comments above, you can try something more like:
$result = mysql_query('SELECT a.eventid, a.summary, b.created
FROM event_info a
join event_details b
on a.eventid = b.eventid');
$events = array();
while ($row = mysql_fetch_array($result)){
$event = array();
foreach ($row as $key=>$value){
$event[$key]=$value;
}
$events[] = $event;
}

Getting all email addresses from table

The code below shows one email address as a output but I want to get a list of all
email addresses (seperated by comma) of customer table. How can I get that?
<?php
$SQLstring = "SELECT email FROM customers";
$QueryResult = #mysqli_query($DBConnect, $SQLstring)
or die("<p>Unable to execute the query.</p>" .
"<p> Error code " . mysqli_errno($DBConnect) . ":" . mysqli_error ($DBConnect))."</p>";
$NumRows = mysqli_num_rows($QueryResult);
if ($NumRows == 0)
{
echo "<p>No email found.</p>";
}
else
{
for($i = 1; $i <= $NumRows; $i++)
{
$Row = mysqli_fetch_row($QueryResult);
$email = stripslashes($Row[0]);
echo $email;
}
}
?>
This is mysqli not mysql you're using so things work a little differently...
Assuming you've created your mysqli connection with something like $DBConnect = new msqli( ... );
It's probably better to store the result before you manipulate it; try something like:
$success = $DBConnect->real_query($SQLstring);
if($success) {
$result = $DBConnect->store_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo $row['email'] . "<br />\n"; //for debugging purposes
}
}
$result->free();
Change:
$email = stripslashes($Row[0]);
To:
$email = stripslashes($Row[$i]);
And you should be set
The PHP docs say that mysqli_num_rows may not return the correct number of rows until you've retrieved all rows, so perhaps, instead of using a row count, just keep fetching rows until you run out:
while ($Row = mysqli_fetch_row($QueryResult))
{
$email = stripslashes($Row[0]);
echo $email;
}
EDIT: If you want to store the emails in an array rather than just echoing them, simply change it to this:
while ($Row = mysqli_fetch_row($QueryResult))
{
$email[] = stripslashes($Row[0]);
}
Now $email will be an array containing all of the emails.
use mysql_fetch_assoc in while loop
$NumRows = mysqli_num_rows($QueryResult);
if ($NumRows == 0)
{
echo "<p>No email found.</p>";
}
else
{
while($row = mysql_fetch_assoc($QueryResult)){
$email = stripslashes($row['email']);
echo $email;
}
}

Categories