first column data is missing in while loop when mysql_fetch_array() - php

i have a problem with while loop.In this first column data is not getting remaining data is getting here is my code
$result_By_Vendor_And_Title = mysql_query("select * from cek6q_jshopping_products where vendor_id = " . $vendor . " and name_en-GB='" . $title . "'");
if (mysql_fetch_array($result_By_Vendor_And_Title)) {
echo 'found';
while ( $rows = mysql_fetch_array($result_By_Vendor_And_Title) ) {
echo $id = $rows['product_id'];
}
}
echo 'not found';
Here i want to display all the ids but i have getting all the ids except first one how i can get first one.

Because the fetch_array you do to test for found is fetching and discarding the first row
just try this
$result_By_Vendor_And_Title = mysql_query("select * from cek6q_jshopping_products where vendor_id = '" . $vendor . "' and name_en-GB='" . $title . "'");
if($result_By_Vendor_And_Title){
if(mysql_num_rows($result_By_Vendor_And_Title)>0){
echo 'found';
while ( $rows = mysql_fetch_array($result_By_Vendor_And_Title) ) {
echo $id = $rows['product_id'];
}
}else{
echo 'not found';
}
}

Try:
if( mysql_num_rows( $result_By_Vendor_And_Title ) > 0 ) {
echo 'found';
while ( $rows = mysql_fetch_array($result_By_Vendor_And_Title) )
{ echo $id = $rows['product_id']; }
}else{
echo 'not found';
}
Dont use mysql_* functions.

Related

For each results- Mysql - JSON

How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.

PHP code execution sequence

I am trying to execute some lines of php code, but it seems that tey are not being execute in the required order. Here is a code snippet:-
if( !empty($_POST['val']) )
{
$val = Get_Val($sid, $_POST['val'], $lnk);
if($val)
{
echo "<br />Here Value : " . $val;
}
else
{
echo "Invalid Value.";
}
}
When I echo the value before returning in function Get_Val() it shows a positive number for some set of valid arguments, which means that the If-condition is true, but when I execute the code the Else part is being executed. Though the output appear in order, they are not consistent. I hope I have made the problem clear.
Any amount of help is appreciated. Thanks!
Here is Get_Val() function:-
function Get_Val( $sid, $a, $link)
{
//check is name is already present in table
$query = "SELECT val FROM store WHERE name = \"" . $a . "\""; //val is auto incremented in sql
$result = mysql_query( $query ,$link ) or die( mysql_error());
if($result)
{
$count = mysql_num_rows($result);
if( $count == 0 ) //insert name and the return val
{
$query_x = "INSERT INTO store(name) VALUES('" . $a . "')";
$result = mysql_query( $query_x ,$link ) or die( mysql_error());
if($result)//If new name inserted then return the 'val'
{
Get_Val($sid, $a,$link);
}
}
else
{
$row = mysql_fetch_assoc( $result );
echo "Val in Get_Val : " . $row['val'];
return $row['val'];
}
}
else
{
echo "Unexpected Error Occured...!!!";
exit(0);
}
}
what's with this:
if( $count Val in Get_Val : " . $row['val'];
return $row['val'];
}
are you sure that $_POST['val'] is a valid value that is stored in the db?
Get_Val does not return a value if $count == 0. Add a return statement before the recursive call. Like this:
...
if( $count == 0 ) //insert name and the return val
{
$query_x = "INSERT INTO store(name) VALUES('" . $a . "')";
$result = mysql_query( $query_x ,$link ) or die( mysql_error());
if($result)//If new name inserted then return the 'val'
{
return Get_Val($sid, $a,$link);
}
}
...

Repeating a query

I want to search a table by inputing a random number for the ID, and for it to be successful, it has to match the specified tag. So far I have:
$query = "SELECT * FROM web_db WHERE P_Id = " . $random;
$result = mysql_query($query);
if($result) {
while($row = mysql_fetch_array($result)){
$name = $row[$id];
echo 'ID:' . $name . '<br>';
$name = $row[$url];
echo 'URL: ' . $name . '<br>';
$name = $row[$tag];
echo 'Tag:' . $name . '<p>';
}
}
This brings up one entry, any tag. How can I have it repeat until Tag matches a specified value?
You don't. SELECT statement returns everything that matches the followed conditions. So, if you want to query for a specific tag entry disregarding the P_Id, do this :
$query = "SELECT * FROM web_db WHERE tag = '".$tag."' ORDER BY RAND() LIMIT 1";
RAND() in this case will order the list randomly, while the query returns the first result that matches the tag used.
$result = mysql_query($query);
if(count($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo 'ID:' . $row['id'] . '<br>';
echo 'URL: ' . $row['url'] . '<br>';
echo 'Tag:' . $row['tag'] . '<p>';
}
} else {
echo 'no entries found';
}
if("sometag" === $name) break;
that exits the while loop. after you exit, you should check again to see if the tag was found or not

When using MySQL request in foreach, first select is good, but then not

With this code:
foreach ($content as $value) {
$data=$value[0];
echo $data;
$req="SELECT * FROM TABLE WHERE data='$data'";
$result=mysql_query($req) or die ('Erreur :'.mysql_error());
if (mysql_num_rows($result)){
echo ' ENTRY EXISTS';
}
else {
echo ' ENTRY DOES NOT EXIST';
}
}
For the first $value it finds an entry, which is correct. For the next ones it doesn't, but it should. How can this be fixed?
Update code
With this code:
$found_list = array();
$fetch_list = array();
foreach($content as $value){
$fetch_list[] = "'" . mysql_real_escape_string($value[0]) . "'";
}
if( empty($fetch_list) ){
echo '<p>No data to fetch</p>';
}else{
$sql = 'SELECT DISTINCT inst_name
FROM INSTITUTS
WHERE inst_name IN (' . implode(', ', $fetch_list) . ')';
$res = mysql_query($sql)
or die ('Error: ' . mysql_error());
while( $row = mysql_fetch_assoc($res) ){
$found_list[] = $row['inst_name'];
}
var_dump($found_list);
}
foreach($content as $value){
echo '<br/>';
echo $value[0] . ' ';
if( in_array($value[0], $found_list) ){
echo "ENTRY EXISTS\n <br/>";
}else{
echo "ENTRY DOES NOT EXIST\n <br/>";
}
}
And the result is :
array(3) { [0]=> string(13) "AixEnProvence" [1]=> string(19) "AixEnProvenceAnnexe" [2]=> string(7) "Acheres" }
acheres ENTRY DOES NOT EXIST
AixEnProvence ENTRY EXISTS
aixenprovenceannexe ENTRY DOES NOT EXIST
instituttest ENTRY DOES NOT EXIST
There is no reason to flood the MySQL server with almost identical queries. Have a look at the IN expression:
SELECT foo, bar
FROM table
WHERE data IN ('a', 'b', 'c');
I also suggest you google for SQL Injection and XSS attacks.
Edit: Here's some code that solves the problem as described in latest comments:
<?php
// $content = ...
$found_list = array();
$fetch_list = array();
foreach($content as $value){
$fetch_list[] = "'" . mysql_real_escape_string($value[0]) . "'";
}
if( empty($fetch_list) ){
echo '<p>No data to fetch</p>';
}else{
$sql = 'SELECT DISTINCT data
FROM table
WHERE data IN (' . implode(', ', $fetch_list) . ')';
$res = mysql_query($sql)
or die ('Error: ' . mysql_error());
while( $row = mysql_fetch_assoc($res) ){
$found_list[] = $row['data'];
}
}
foreach($content as $value){
echo $value[0] . ' ';
if( in_array($value[0], $found_list) ){
echo "ENTRY EXISTS\n";
}else{
echo "ENTRY DOES NOT EXIST\n";
}
}
?>
Answer to updated question:
PHP comparison operators are case sensitive:
<?php
var_dump('Acheres'=='acheres'); // bool(false)
?>
You can use strtolower() to normalize values before comparing.

Retrieving values from MySQL

I have a very simple table that contains a list of 'victims' and the corresponding number of that type destroyed. I'm trying to make an output page of this information, using this code:
foreach( $victims as $vic )
{
$hits = mysql_query("SELECT amount
FROM victims
WHERE victim = ".$vic );
echo $hits;
print "$vic: $hits <br /><hr>";
}
However, hits comes out empty. What's wrong with my SQL query?
foreach($victims as $vic)
{
$hits = mysql_query('SELECT amount
FROM victims
WHERE victim = "' . mysql_real_escape_string($vic) . '"');
if($hits && mysql_num_rows($hits)>0) {
while($row = mysql_fetch_array($hits)) {
echo '<p>' . $row['amount'] . ' hits</p>';
}
} else {
echo '<p>' . mysql_error() . '</p>';
}
}
mysql_query() doesn't return the actual result of your query, but rather a resource with which you can then access the results.
This is a typical pattern:
$result = mysql_query(...);
$row = mysql_fetch_assoc($result);
print($row['amount']);
Each call to mysql_fetch_assoc returns the next row of the result set. If you were expecting multiple rows to be returned, you can call this in a while loop:
$result = mysql_query(...);
while ($row = mysql_fetch_assoc($result)) {
print($row['amount']);
}
Since there's no sane error checking in any of the answers, I'll put the whole thing in here:
foreach( $victims as $vic )
{
$sql = "SELECT amount
FROM victims
WHERE victim = '".mysql_real_escape_string($vic)."'";
$result = mysql_query($sql);
$result or die('Query Error: '.mysql_error() . ' - ' . $sql);
$hitsarray = mysql_fetch_assoc($result);
if ($hitsarray) {
$hits = $hitsarray['amount'];
} else {
// No row was found
$hits = 0;
}
echo $hits;
print "$vic: $hits <br /><hr>";
}
Oh, and this fixes the query error that caused the issue in the first place. Note the quotes wrapping the $vic variable in the string, as well as the proper escaping of the string...

Categories