Couldn't get data from another table in MySQL - php

I am currently trying to get a data(M_Name) from a table called Merchant.
Following are my codes:
<?php
$response = array();
$link = mysql_connect('localhost','root','') or die ('Could not connect: '.mysql_error());
mysql_select_db('ichop') or die ('Could not connect to database');
$result = mysql_query("select * from offer") or die(mysql_error());
if(mysql_num_rows($result) > 0){
$response["offers"] = array();
while($row = mysql_fetch_array($result)){
$offer = array();
$offer["offer_id"] = $row["Offer_ID"];
$offer["start_date"] = $row["Start_Date"];
$offer["end_date"] = $row["End_Date"];
$offer["o_desc"] = $row["O_Desc"];
$offer["short_desc"] = $row["Short_Desc"];
$offer["merchant_ID"] = $row["Merchant_ID"];
$offer["m_name"] = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'");
array_push($response["offers"], $offer);
}
$response["success"] = 1;
echo json_encode($response);
} else {
//no offer found
$response["success"] = 0;
$response["message"] = "No offer found";
echo json_encode($response);
}
?>
When I run this PHP file using web browser, I couldn't get the desired name for the merchant even though the data is there in the database...it would just return me "null".
{"offers":[{"offer_id":"1","start_date":"2013-05-17","end_date":"2013-05-18","o_desc":"AAA","merchant_ID":"2","m_name":null}],"success":1}
What have I done wrong or what am I still missing? Please help..thanks!

I would rather use LEFT JOIN mysql function and get all relevant data at first query from both of your tables
SELECT * FROM offer a LEFT JOIN MERCHANT b ON a.Merchant_ID = b.MERCHANT_ID
so you won't have to make any extra query and you can store your value directly in your array
$offer["m_name"] = $row['M_Name'];
Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO

The mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'"); does not return a value from the DB, you need to follow it up with for example mysql_fetch_array like you did with the other query to the DB.
There is a solution more simple: use a JOIN, which combines two tables.
SELECT offer.*, MERCHANT.M_Name
FROM offer
LEFT JOIN MERCHANT ON(MERCHANT.MERCHANT_ID = offer.merchant_ID)

look like you have to return an result from query instead of while,
mysql_fetch_array(mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'"));
but had better you make some error hadling first

You can use below one
$resMerchant = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'");
$rowMerchant = mysql_fetch_assoc($resMerchant);
$offer["m_name"] = $rowMerchant['M_Name'];

$offer["m_name"] = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'")
mysql_query() does not return a string but a resource. You'll have to fetch the result.
Also, don't forget that mysql_* is now deprecated.
[edit]
As stated by Fabio, you'd rather use JOIN on your query. At the moment, you are making a request in your loop. That's useless (INNER JOIN or LEFT JOIN are what you want) and very resource consumming.

Related

PHP code mysql query isnt working

I created a mysql query to check if user is banned or not and if he's the system give him return false. But it wont get the information.
public static function checkban($username)
{
if(LOGINCHECKBAN == false)
{
$vusername = engine::securyt($username);
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$getNOW = mysql_query($getIdBYname);
$IDbyNAME = mysql_free_result($getIdBYname);
$queryforban = mysql_query("SELECT * FROM bans WHERE data = '".$IDbyNAME."' LIMIT 1");
$query = mysql_num_rows($queryforban);
if($query == 0) {
return true;
} else {
return false;
}
}
}
Note: engine::securyt($username) is the form type to get his username when he try to login.
What can be wrong on my code?
edit: I belive that "mysql_free_result" can be the problem, but im not sure what i need to put on replace of it.
mysql_free_result() frees a mysql result set. It does not actually retrieve data from the result.
You will want something like:
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$result = mysql_query($getIdBYname);
$row = mysql_fetch_assoc($result);
if($row) { //a user was found
//$row['id'] is the found user
$result = mysql_query("SELECT COUNT(*) cnt FROM bans WHERE data = '". $row['id'] ."' LIMIT 1");
$row = mysql_fetch_assoc($result);
return ($row && $row['cnt'] == 0);
} else {
// no user; return something appropriate
}
However, if all you need is to determine is whether a particular user name is banned (and not actually get their user id), you can do that directly in the database with one query:
SELECT COUNT(*)
FROM players p
INNER JOIN bans b ON b.data = p.id
WHERE p.username = $username;
WARNING: Note that using mysql_* functions is strongly discouraged for new code (since mysql_* has been removed in PHP 7), and directly including variables in your query strings is a pretty major security vulnerability. You should look into using prepared statements/parameterized queries with mysqli or PDO.

Using PHP while loop to retrieve specific data and post it on a google map

Hi im relatively new to PHP and very new to google maps API but I would like to retrieve data from my mysql database and post it onto my google map, the problem is that I need to search database A for relevant data, pull an 'id' from each entry then search database B for all the ids pulled and finally use the data pulled from database B to place a marker on a google map (database B holds the 'id' to correspond with database A a latitude field and a longitude field). I hope all this makes sense after reading my code:
<?PHP
$min = $_POST['min'];
$result = mysqli_query($con,"SELECT * FROM A WHERE x>".$min);
while($row = mysqli_fetch_array($result))
{
$host=$row['host_id'];
$result1 = mysqli_query($con,"SELECT * FROM B WHERE host_id=".$host);
while($row1 = mysqli_fetch_array($result1));
{
$lat2=$row1['latitude'];
$lon2=$row1['longitude'];
echo 'var myLatLng = new google.maps.LatLng('.$lat2.','.$lon2.');';
echo 'var aMarker = new google.maps.Marker({';
echo 'position: myLatLng,';
echo 'map: map,';
echo '});';
}
}
?>
As I said im pretty new to PHP so any help as to where im going wrong here would be greatly appreciated
Thanks :)
You can connect to two different databases at the same time. With the mysqli_ extension you are using:
<?php
$db1 = mysqli_connect('localhost',$username1,$password1);
mysqli_select_db($db1, $database1) or die( "Unable to select database 1");
$db2 = mysqli_connect('localhost',$username2,$password2);
mysqli_select_db($db2, $database2) or die( "Unable to select database 2");
?>
Then you can choose either $db1 or $db2 as needed.
<?php
$min = (int) $_POST['min'];
$result = mysqli_query($db1,"SELECT * FROM A WHERE x>".$min);
while($row = mysqli_fetch_array($result))
{
$host=$row['host_id'];
$result1 = mysqli_query($db2,"SELECT * FROM B WHERE host_id=".$host);
while($row1 = mysqli_fetch_array($result1));
{
//...
}
}
?>
I have added an (int) to sanitise your $_POST['min'] variable - this is important to guard against SQL injection. For strings, you should investigate using mysqli_real_escape_string(), or even better, go for parameterised queries: How can I prevent SQL injection in PHP?
Update
For tables in the same database, I would recommend reconfiguring your code to use a single SQL statement, and JOIN the tables together. Something like:
<?php
$sql = "
SELECT B.latitude, B.longitude
FROM B
INNER JOIN A ON (A.host_id = B.host_id)
WHERE A.x > {$min}
";
?>
This gets all records from B which have a host_id which matches any host_id in A with a value of x greater than $min. You will get duplicates if you have multiple records in A with the same host_id, so you could add a GROUP BY clause to reduce these, either on host_id, or on the primary key of table B, if this is not host_id:
...
WHERE A.x > {$min}
GROUP BY B.host_id
Also, it's probably worth checking the SQL for errors and displaying a warning:
<?php
$result1 = mysqli_query($con,$sql);
if($result1===FALSE)
{
$sql_error = mysqli_error($con);
$js_safe_sql_error = json_encode(utf8_encode($sql_error));
echo "alert('Database Error: ' + " . $js_safe_sql_error . ");\n";
}
else
{
while($row1 = mysqli_fetch_array($result1));
{
//...
}
}
?>
I notice in your comment you say that the map completely disappears though. This would indicate an error in the generated javascript. Hopefully your browser's javascript console will display this error. When I run it I get: ReferenceError: map is not defined, but this is probably being defined elsewhere in your code?

how to get a particular field from a database via php

I am trying to get four different values from my database. The session variable username and usernameto are working, but I want to get 4 different values -- two each from username and usernameto:
<?php
session_start(); // startsession
$Username=$_SESSION['UserID'];
$Usernameto= $_SESSION['UserTO'];
$db = mysql_connect("at-web2.xxxxxx", "yyyyy", "xxxxxxx");
mysql_select_db("db_xxxxxx",$db);
$result1 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon and user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
while($myrow1)
{
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
while($myrow2)
{
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
?>
Edit - just realized that you didn't tell us what wasn't working about the code you provided. Are you getting an error message or are you not getting the correct data back? You still should fix your query, but we'll need some more information to know what's wrong.
Your query statements shouldn't have "and" between the select parameters, so it should be:
Edit 2 - I just noticed that you had a while loop that you don't need, try this:
$result1 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Usernameto'");
$result2 = mysql_query("SELECT user_lon, user_lat FROM table1 WHERE id = '$Username'");
$myrow1 = mysql_fetch_row($result1);
$myrow2 = mysql_fetch_row($result2);
if (isset($myrow1)) {
$_Mylon=$myrow1[0];
$_Mylat=$myrow1[1];
}
if (isset($myrow2)) {
$_Mylon2=$myrow2[0];
$_Mylat2=$myrow2[1];
}
An example from the php manual echoing an html table
I don't know if you can derive what you need from this?
More specific: You can use:
$line = mysql_fetch_array($result, MYSQL_ASSOC);

MYSQL does not return result in PHP when asked for the first ranking only

I am trying to get hold of 1 record from a MySQL table using PHP. I have tried many different SELECT statements, while they all work in MYSQL they refuse to return any result in php.
The countriesRanking table is a simple two column table
country clicks
------ ------
0 222
66 34
175 1000
45 650
The mysql returns the ranking of the country column (1, 2, 3, etc..) and it returned all results EXCEPT the first ranked country. Eg when country=175, should return 1 but no result returned. Direct query via web browser return blank page, no error message. My PHP code
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country'") or die(mysql_error());
$row = mysql_fetch_assoc($result) or die(mysql_error());
$theranking = $row['rank'];
echo $theranking;
EDIT
I tried the following but get the same blank page
var_dump($row['rank']);
EDIT 2
For a successful query print_r($result) returned something like Resource id #4. While print_r($row) returned Array ( [0] => 4 [rank] => 4 ). But when querying for the top ranking country. eg country=175, it returned a blank page.
Give this a try. It is based on your earlier question. MYSQL returns empty result in PHP
MYSQLI version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysqli_connect($hostname,$user,$password,$database);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 175";
$result = mysqli_query($link,$query);
$arr_result = mysqli_fetch_array($result,MYSQLI_BOTH);
return $arr_result['rank'];
}
mysqli_close($link);
}
echo rank();
?>
MYSQL version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysql_connect($hostname,$user,$password);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 66";
mysql_select_db($database);
$result = mysql_query($query);
$arr_result = mysql_fetch_array($result,MYSQL_BOTH);
return $arr_result['rank'];
}
mysql_close($link);
}
echo rank();
?>
Assuming you are not getting an error that means you are successfully connecting to your database. You are just not getting back any values.
Try:
$row = mysql_fetch_row($result);
I would usually think $row = mysql_fetch_assoc($result); would work but if neither of these work it must be something within your mysql_query.
You can debug this as below.
make sure your SQL is correct by running it on PHPMyAdmin and check the result.
make sure you don't have any fatal errors, if you get a blank page there is something wrong. Turn on PHP errors and see.
print_r($result) and see whether it's empty.
if you want first ranking only then add the LIMIT 1 to your query
If you want only one record from database than you have to use limit in query
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country' LIMIT 1") or die(mysql_error());
and after that use while loop
while($row = mysql_fetch_assoc($result)) {
$theranking = $row['rank'];
}
echo $theranking;

MySQL query WHERE statement which is a query itself?

So I'll try to clearly explain my goal first:
First, I want to query one table in my database for a list of usernames.
Second, I want to take those usernames, and query another table in the database and return only the rows in which these usernames appear in the username field.
Finally, I want to take this output (in JSON array form right now), and return it to the requesting client.
My query looks like this right now:
$query = mysql_query("SELECT * FROM tagusers WHERE username =
(SELECT userA FROM friendtable WHERE userB = '$username')");
This works when the WHERE statement yields 1 result. So if I only get one returned userA, it works fine. But if I get multiple, I get a bunch of errors.
Here is the code in its entirety:
if (isset($_POST['username'])) {
$username = $_POST['username'];
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("TagDB");
$query = mysql_query("SELECT * FROM tagusers WHERE username =
(SELECT userA FROM friendtable WHERE userB = '$username')");
}
while ($e = mysql_fetch_assoc($query)) {
$output[] = $e;
}
$output = json_encode($output);
print $output;
I get the following error on the query line:
*Warning: mysql_query() [function.mysql-query]: Unable to save result set in C:\wamp\www\tag\appgetfriendinfo.php on line 21*
So all I really need to know is, how would I write that query in MySQL so that I get returned an array of rows?
You don't need a subquery at all, you'll usually get better performance out of a join. Make sure you have indexes defined on tagusers.username, friendtable.userA and friendtable.userB
SELECT
tagusers.*
FROM
tagusers
INNER JOIN
friendtable
ON
tagusers.username = friendtable.userA
AND
friendtable.userB = '$username'
Use the IN keyword.
$query = mysql_query("SELECT * FROM tagusers WHERE username IN
(SELECT userA FROM friendtable WHERE userB = '$username')");
Use either the IN clause, or a JOIN like in this example:
$query = sprintf("SELECT tu.*
FROM TAGUSERS tu
JOIN FRIENDTABLE ft ON ft.usera = tu.username
WHERE ft.userB = '%s'",
mysql_real_escape_string($_POST['username']));
$result = mysql_query($query);
$output = json_encode($result);

Categories