mysql_fetch_array to compare data between 2 tables using php? - php

I'm attempting to utilize 2 mysql tables via php/mysql 2 get me a max value. I'm assuming using an array is the correct way to do this, but I've been spending many hours and am missing something.
My tables are:
1) plantcomp, where I want to know all the CompressID listings that have a CustID of $CustID. (there are currently 3).
2) comps, where I want to use those CompressID listings to know the valid Compressor #s. I'll then do a max() on those values so I can name the next compressor max()+1.
My code attempts...This gets me an error: "Notice: Array to string conversion in (pathname) on line 55", then "Array"
//have the custid
echo $CustID;
//under table `plantcomp`, find matching compressid's.
$q55 = "SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "' ";
// Run query
$result55 = mysql_query($q55);
while($row = mysql_fetch_array($result55)){
echo "<p>".$row;
I also tried this, mysql_fetch_assoc, but it only gives me 2 of my 3 valid entries...
$get = mysql_query("SELECT CompressID FROM plantcomp WHERE CustID = '$CustID'");
$money = mysql_fetch_assoc($get);
while($money = mysql_fetch_assoc($get)){echo $money['CompressID'];}
Thank you in advance for your assistance!!

Please change this line
echo "<p>".$row;
to
echo "<p>";
print_r($row);

The problem you have comes from the fact that you are mixing a string (<p>) with an array ($row).
echo "<p>".$row;
You can print the $row array by using print_r:
print_r($row);
You can also access different elements of the $row array (table columns) like this:
$row['column_name'];
For example, lets say your table consists of two columns: first_name and last_name. You can print them like this:
echo '<p>' . $row['first_name'] . ' ' . $row['last_name'] . '</p>';
So, with that knowledge, we can print your CompressIDs:
$result55 = mysql_query("SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "'");
while ($row = mysql_fetch_assoc($result55))
{
echo '<p>' . $row['CompressID'] . '</p>';
}

$CompressID = array(); //Initialising an array
$query = "SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "' ";
$result = mysql_query($query);
while($obj = mysql_fetch_assoc($result)){
$CompressID = $obj['CompressID']; //Storing all the CompressID in an array
echo $obj['CompressID']; // sanity check
}
First run the above query and compare result with db.If the result is not matching
1)There is some wrong data in db
2)Alter your query to get desired result.
If this is working then add rest of the code
if( count($CompressID) >0 ){
$query = "SELECT max(CompressID) as maxCompressID FROM `comps` WHERE `CompressID` IN($CompressID)";
$result = mysql_query($query);
while($newObj = mysql_fetch_assoc($result){
echo $newObj['maxCompressID'];
}
}

Related

how do i display all records of a field using php in a mysql database

So i want to get all records of a specific field in a table using mysql database
so far i tried this but it only echos the first ever record in that field
$query = ("SELECT txtpath,txtname FROM txtdocs WHERE subject='$ref'");
$result = mysql_query($query);
$count = mysql_num_rows($result);
//iterate over all the rows
while($row = mysql_fetch_assoc($result)){
//iterate over all the fields
foreach($row as $key => $val){
//generate output
echo $key . ": " . $val . "<BR />";
}
}
Also yes i have more than 1 record in my database
Edit: I added 1 more row so i can have a total of 3 rows, but it's only showing me 2 out of 3 records now.
I think this will work!
//$dbname= 'your connection to database';
$result = mysqli_query($dbname, 'SELECT txtpath,txtname FROM txtdocs WHERE subject="'.$ref.'"');
$count = mysqli_num_rows($result);
//iterate over all the rows
while($row = mysqli_fetch_assoc($result)){
echo $row['txtpath'] . ': ' .$row['txtname']. '<br/>';
}
No need to use loop inside the loop:
while($row = mysql_fetch_assoc($result))
{
echo $row["txtname"] . ": " . $row["txtpath"]. "<br/>";
}
UPDATE 1:
If value if $ref is ENGLISH than your query must return three records not two. Now you need to debug further NY checking the column value maybe you have some space around column value like " ENGLISH".
UPDATE 2:
Further more execute your SELECT query in phpmyadmin and check how many rows return.
SELECT txtpath,txtname FROM txtdocs WHERE subject="English";
Side note:
Please use mysqli_* or PDO instead of mysql_* its deprecated and not available in PHP 7.
I am pretty sure that you can't explain and can't listen. I guess:
You have 3 records in table now, yes?
Before You had 2 records and displays only one.
Next you added new record and displays 2 of 3.
In your SQL query you have WHERE statement => I guess that record which not displayed does not satisfy the condition.
The easiest way to check this is dump/echo $count.
Can you display this? If result is 2 I am right, if not we can think further.
UNFORTUNATELLY people don't think yourself, just ask and lose your time and other.
If you want to display all record of a specific field in a table, you have to remove "where" condition because if condition contain only one column in table then it will be display only one record.
$query = ("SELECT txtpath,txtname FROM txtdocs");
$result = mysql_query($query);
$count = mysql_num_rows($result);
//iterate over all the rows
while($row = mysql_fetch_assoc($result)){
//iterate over all the fields
foreach($row as $key => $val){
//generate output
echo $key . ": " . $val . "<BR />";
}
}

Compare rows in PHP

Hi I would like to compare two tables from two different databases.
Select from the first database
$sql= mysqli_query ("SELECT * FROM emasa.staff_detail");
$row = mysqli_fetch_array($sql);
Select from the second database
$sql2 = mysqli_query ("SELECT * FROM employee");
$row2 = mysqli_fetch_array($sql2);
Then I compare the two table
if ($row['icnum'] == $row2['emp_ic'])
{
echo "Data already exist in both database.";
}
else
{
while ($row = mysqli_fetch_assoc($sql))
{
echo "<td align='center' height='30'>" . $row ['name'] . "</td>";
echo "<td align='center'>" .$row['icnum'] . "</td>";
}
}
But my problem is it only compares the first row in the database.
My output should only display the staff name that is not available in the other database. However, this is my output.
Based on the output it only compares the first row. So how do I change my code so that it compares the whole row. Please help me, thank you!
You're not looping through the results of the query. You're simply getting back the first row and going with that.
Ex:
$sql= mysqli_query ("SELECT * FROM emasa.staff_detail");
This is returning a result set which you then need to use
$row = mysqli_fetch_array($sql);
to get the actual values. The problem comes when
$row = mysqli_fetch_array($sql);
by itself only gives you one row.
Solution 1
You must use code like this:
while($row = mysqli_fetch_array($sql))
{
//Do some comparison
}
Since you're going to have to loop through two different result sets, you're going to have to do a loop within a loop, build an array of results and then loop through the results afterwards to output your HTML.
Ex:
while($row = mysqli_fetch_array($sql))
{
while($row2 = mysqli_fetch_array($sql2))
{
if ($row['icnum'] == $row2['emp_ic'])
{
//add to array of equal data
}
else
{
//add to array of not equal data
}
}
}
foreach($array as $not_equal_or_equal_data)
{
//output your desired HTML
}
Solution 2
Depending on what you actually care about, you could do a sql statement like this
$sql = "
SELECT
*
FROM
emasa.staff_detail AS sd
JOIN db2.employee AS e
ON sd.icnum = e.emp_ic";
This would return all the rows where those two columns were equal

Query Result: What is $row[0]

I know this may sound like a stupid question from a programming-newbie, but I just want to make sure I understand correctly.
After a query, what does $row[0] stand for/ result in?
Is my understanding correct that $row[0] shows ALL results?
HERE ARE EXAMPLES:
$query = "SELECT count(commentid) from comments where jokeid = $jokeid";
$result = mysql_query($query);
$row=mysql_fetch_array($result);
if ($row[0] == 0)
{
echo "No comments posted yet. \n";
} else
{
echo $row[0] . "\n";
echo " comments posted. \n";
AND THIS ONE
$query = "Select count(prodid) from products where catid = $catid";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if ($row[0] == 0)
{
echo "<h2><br>Sorry, there are no products in this category</h2>\n";
}
else
{
$totrecords = $row[0];
Thanks in advance.
$row[0] will simply echo the first column in your database.
0 is the first because all arrays in PHP (and in most programming languages) are zero-based - they simply start with zero.
$row[0] will be the value of the first column in your results. If you use mysql_fetch_assoc($result) you will have an array in the form:
array(column_name => column_value);
e.g.
$row = mysql_fetch_asssoc($result);
$value_column_1 = $row['column_1'];
You can also use mysql_fetch_object($result) to get an object with column names as the parameters.
$row = mysql_fetch_object($result);
$value = $row->column_name
mysql_fetch_array() takes the next (in your examples first) row out of the resultset and stores the data in an array $row.
$row[0] now represents the first value of that row.
So in total in your examples the variable holds the first value of the first row of your resultset.

SQL query is only retrieving first record

I have a query which is designed to retireve the "name" field for all records in my "tiles" table but when I use print_r on the result all I get is the first record in the database. Below is the code that I have used.
$query = mysql_query("SELECT name FROM tiles");
$tiles = mysql_fetch_array($query);
I really cant see what I have done wrong, I have also tried multiple searches within google but I cant find anything useful on the matter at hand.
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
echo "<br />";
}
?>
'mysql_fetch_array'
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
This means that it returns array (contains values of each field) of A ROW (a record).
If you want other row, you call it again.
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
// Do something with $row
}
Hope this helps. :D
Use "mysql_fetch_assoc" instead of "mysql_fetch_array".
$query = mysql_query('SELECT * FROM example');
while($row = mysql_fetch_assoc($query)) :
echo $row['whatever'] . "<br />";
endwhile;
I believe you need to do a loop to invoke fetch array until it has retrieved all the rows.
while ($row = mysql_fetch_array($query) ) {
print_r( $row );
}

How do I loop through a PHP array containing data returned from MySQL?

Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}

Categories