MySQL query receives only 1 result - php

I have the following code which displays only 1 result. However, I have six rows in my database with product_id = '1'. I'm talking about $order, only one shows up, instead of six. What is wrong?
$get = "SELECT * FROM artikelbestelling WHERE product_id = '1' LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while($row = mysql_fetch_assoc($doget))
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo "<strong>$order</strong><br />";
}
My database structure:
id (primary & autoincrement)(int 11)
product_id (int 11)
number (int 11)
ordernummer (int 11)

as your id is int, you dont need to use ''
$get = "SELECT * FROM artikelbestelling WHERE product_id = '1' LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while($row = mysql_fetch_array($doget))
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo "<strong>$order</strong><br />";
}

try this.....
$get = "SELECT * FROM artikelbestelling WHERE product_id = '1'
LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while($row = mysql_fetch_array($doget))
{
echo "$row[ordernummer]";
echo "<br />";
echo "$row[artikelnummer]";
}

There are two things that I notice immediately that shouldn't make a difference, but might be worth trying just to see if it does. First, assuming that the product_id column is a numeric column instead of a string, try using just 1 instead of '1'. Second, explicitly check the result of mysql_fetch_assoc() against FALSE instead of any expression that might evaluate equivalent to false.
$get = "SELECT * FROM artikelbestelling WHERE product_id = 1 LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
while(($row = mysql_fetch_assoc($doget)) !== FALSE)
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo "<strong>$order</strong><br />";
}
Edit:
What do you get if you change your code to the following?
$get = "SELECT * FROM artikelbestelling WHERE product_id = 1 LIMIT 0, 500";
$doget = mysql_query($get) or die(mysql_error());
$index = 0;
while(($row = mysql_fetch_assoc($doget)) !== FALSE)
{
$order = $row['ordernummer'];
$artikel = $row['artikelnummer'];
echo $index++ . ": <strong>$order</strong><br />";
}
Specifically, does it count all the way from 0 to 7, or does it just show row 0? I'm thinking that it's got to be one of the following:
You really are only getting back one row of results (which is contradicted by your statement that mysql_num_rows() is returning 8),
mysql_fetch_assoc() is incorrectly returning FALSE after just one row (which indicates some kind of bug affecting PHP or the MySQL driver, which is typically very unlikely), or
it is iterating through the loop like it should be, but you are misinterpreting the result, per Marc B's comment regarding empty tags.
This might effectively help narrow down which it is.

Related

PHP - divide two values

I'm having problem on dividing two values and it keeps showing
Warning: Division by zero in ...
I've read and tried some post about dividing values in here but I can't still solve the problem.
This is the snippet :
$query2 = "SELECT SUM(jumlah_poin) AS jumlah_mk FROM tbl_nilai WHERE nama_mk = 'Pengantar Teknologi Informasi'
AND nip_dsn = '198'";
$result2 = mysql_query($query2);
$row2 = mysql_fetch_assoc($result2);
$query4 = "SELECT count(1) FROM tbl_nilai WHERE nama_mk = 'Pengantar Teknologi Informasi'
AND nip_dsn = '198'";
$result4 = mysql_query($query4);
$row4 = mysql_fetch_array($result4);
$sum ['jumlah2']= $row2 ['jumlah_mk'] / $row4 [0];
echo json_encode(array($resultArray,$sum));
and I need to make it in one echo. Any explanation you can provide to a newb will be appreciated. help and teach me please :D
To prevent the devide by zero error I might put it in an if statement
if( $row4[0] != 0 ) { // any falsy value would evaluate to zero
$sum ['jumlah2']= $row2 ['jumlah_mk'] / $row4 [0];
} else {
$sum = $sum_default_value;
}
There are two reasons, try one of this:
Change query to
$query4 = "SELECT count(1) as totalCount FROM tbl_nilai WHERE nama_mk ='Pengantar Teknologi Informasi' AND nip_dsn = '198'";
and
$sum ['jumlah2']= $row2 ['jumlah_mk'] / $row4 ['totalCount'];
Your 2nd query returns count as 0, if no record match.

Predefined counter not updating in select statement

Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";

php return last row with truncate (sbstr)

I've got just a quick problem. I've got code that returns the last post for separate titles for a forum. I want to limit the number of characters shown and put the (... …).
I'm having difficulty with a nested if statement in my while loop:
$query = "SELECT comment FROM Assembly WHERE title = 'Checkered' ORDER BY date DESC LIMIT 1";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($message))
{
if(strlen($message) > 10)
{
echo substr($message, 0, 10)."…";
}
else
{
echo "Last Post:<br>";
echo strip_tags("{$row['comment']}");
}
}
thanks in advance :)
**edit
yes css text-overflow:ellipsis; works great!! Thanks guys
***edit working code incase you want
$query = "SELECT comment FROM Assembly WHERE title = 'Checkered' ORDER BY date DESC LIMIT 1";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$comment = strip_tags($row['comment']);
if(strlen($comment) > 30)
{
echo substr($comment, 0, 30)."...";
}
else
{
echo "Last Post:<br>";
echo $comment;
}
}
The problem you have with your code is that you have some badly named variables. You assign the result resource returned by mysql_query() to $result, you then try and fetch a row from a variable called $message (which you don't show the assignment of) and you then switch to treating $message as if it were a string, rather than manipulating the value in $row.
Regardless of that, if you just want to fetch the string from the DB and apply an ellipsis, and you don't need the full text, I would get MySQL to do the work for me:
SELECT IF(CHAR_LENGTH(`comment`) > 10, CONCAT(SUBSTRING(`comment`, 1, 10), '...'), `comment`) AS `comment`
FROM `Assembly`
WHERE `title` = 'Checkered'
ORDER BY `date` DESC
LIMIT 1
In PHP:
$query = "
SELECT IF(CHAR_LENGTH(`comment`) > 10, CONCAT(SUBSTRING(`comment`, 1, 10), '...'), `comment`) AS `comment`
FROM `Assembly`
WHERE `title` = 'Checkered'
ORDER BY `date` DESC
LIMIT 1
";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo "Last Post:<br>";
echo htmlspecialchars($row['comment']);
}
EDIT
Following #Jared's comments about the potential for broken strings displaying partial HTML tags, here is the way to do it that will avoid this:
$query = "
SELECT `comment`
FROM `Assembly`
WHERE `title` = 'Checkered'
ORDER BY `date` DESC
LIMIT 1
";
$result = mysql_query($query);
// Loop is pointless because of the LIMIT 1
$row = mysql_fetch_assoc($result);
$maxlen = 10; // Max length before trim
$comment = strip_tags($row['comment']);
if (strlen($comment) > $maxlen) {
$comment = substr($comment, 0, $maxlen).'...';
}
$comment = htmlspecialchars($comment);
echo "Last Post:<br>";
echo $comment;
You give nout over as to the problem but I am going to go out on a limb and guess the problem. Try this:
while($row = mysql_fetch_assoc($message))
{
$comment = strip_tags($row['comment']);
if(strlen($coment) > 10)
{
echo substr($comment, 0, 10)."...";
}
else
{
echo "Last Post:<br>";
echo $comment;
}
}

SQL QUERY returning all results using OR in WHERE statement

Hoping I am just missing something simple here:
$sql = "Select * FROM user_info, user_login WHERE user_login.status = '0' OR user_login.status = '2' AND user_info.uid = user_login.uid";
$db = new connection();
$results = $db->query($sql);
$user = array();
while($info = mysql_fetch_array($results))
{
$user[] = $info;
}
$total = count($user);
//TEST the amount of rows returned.
echo $total;
for ($i = 0; $i < $total; $i++)
{
//echo data;
}
just trying to pull all data that has the user_login.status field set to "0" or "2" but it shows everything thing and it shows the items marked as 2 twice.
Does anyone see my issue?
Your precedence is getting whacked because of missing parentheses:
SELECT DISTINCT *
FROM user_info, user_login
WHERE (user_login.status = '0' OR user_login.status = '2')
AND user_info.uid = user_login.uid
Without seeing the data I can't give you more than a SELECT DISTINCT with regards to the duplicate records.
Select * FROM user_info, user_login WHERE (user_login.status = '0' OR user_login.status = '2') AND user_info.uid = user_login.uid
Order of precedence :)

how can i controll while loop into another while loop

Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);

Categories