0

I have a php file that should returns value from mysql, her is my php file:

<?php

$host = "localhost"; // Host name 
$username = "UserName"; // Mysql username 
$password = "PassWord"; // Mysql password 
$db_name = "DbName"; // Database name 
$tbl_name = "Notes"; // Table name 

// Connect to server and select databse.
mysql_connect($host, $username, $password)or die("cannot connect"); 
mysql_select_db($db_name)or die("cannot select DB");




// To protect MySQL injection (more detail about MySQL injection)
$mytitle = $_REQUEST['title'];
$mytitle = stripslashes($mytitle);
$mytitle = mysql_real_escape_string($mytitle);

$sql="SELECT * FROM $tbl_name WHERE title = '$mytitle'";


$result = mysql_query($sql);

// Mysql_num_row is counting table row
$count = mysql_num_rows($result);

$count = 0;
$items;

while($row = mysql_fetch_array($result)) {
    $item['userName'] = $row['userName'];
    $item['title'] = $row['title'];
    $item['comments'] = $row['comments'];
    $item['commentsTime'] = $row['commentsTime'];
    $item['commentsDate'] = $row['commentsDate'];
    $items[$count] = $item;
}

echo json_encode($items);

?>

The file does return only one value when I run the code from my browser, I access the file via URL (http://MyWeb.com/ReadNotesByTitle.php?title=titleName).

Can any one tell me what is the wrong with my code? Thanks

3 Answers 3

1

You have missed $count++; inside while loop

Sign up to request clarification or add additional context in comments.

Comments

1

You never increment $count; it always has the value 0. So the second item will overwrite the first, the third will overwrite the second, and so on. Ultimately, you will only return the last row fetched from the database.

Increment $count at the end of the loop to solve the problem:

    $items[$count] = $item;
    $count++;
}

Alternatively, you can append an element to an array without keeping track of the count. Remove the $count variable entirely and change your array assignment to:

$items[] = $item;

Comments

0

While I see this has already been answered I thought I should note you are making your code more complicated than it has to be. You're entire while loop can be summarized as below and will give your desired results

while($row = mysql_fetch_array($result)) {
    $items[] = $row;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.