PHP MySQL WHERE column-value is in $_POST - php

I'm trying to get all the rows which contain a particular text. However, when I execute the query, no rows are returned. I'm retrieving the text from a post request which looks like this "Krachttraining,Spinning" (= 2 values). I think my code fails on the following part (if I leave this out, the query returns some rows): AND CONCAT('%', sport.name, '%') LIKE $sports.
FYI. I know you can perform SQL injection on this, this will be fixed later.
<?php
$servername = "SECRET";
$username = "SECRET";
$dbpassword = "SECRET";
$dbname = "SECRET";
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$sports = $_POST['sports'];
echo $sports; //Echo's: Krachttraining,Spinning.
// Create connection.
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
// Check connection.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT gym.id FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND CONCAT('%', sport.name, '%') LIKE $sports";
$result = $conn->query($sql);
$output = array();
if ($result->num_rows > 0) {
// output data of each row.
while($row = $result->fetch_assoc()) {
$id = $row["id"];
array_push($output, $gym);
}
//Brackets because of GSON's parser.
echo "[" . json_encode($output) . "]";
}
$conn->close();
?>
EDIT: Changed SQL statement to:
$sql = "SELECT * FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND sport.name LIKE '%".$sports."%'";
Still getting 0 rows returned.
EDIT 2: I ran the following code in my phpMyAdmin environment, and it returned 0 rows.
Select * FROM sport WHERE name LIKE '%Krachttraining,Spinning%';
However when I'm running the following code, it returns 1 row:
Select * FROM sport WHERE name LIKE '%Krachttraining%';
I don't really get it what I'm doing wrong, any thoughts?

I think you want to use the IN statement.
This will check if any word in the array matches. For instance:
Select * FROM sport WHERE name IN ('Spinning', 'Krachttraining'); Will return every row which has the name Spinning or Krachttraining.

Just use:
SELECT .FROM...WHERE AND sport.name LIKE '%".$sports."%'";
After question editing
After you changed the question, I suggest to take a look at this answer to better understand what you should to do: https://stackoverflow.com/a/3902567/1076753
Anyway I think that you have to learn a bit about the like command: http://www.mysqltutorial.org/mysql-like/

Change the sql to :
$sql = "SELECT gym.id FROM gym, sport, gym_sport WHERE lat BETWEEN '$lat'-1 AND '$lat'+1 AND lng BETWEEN '$lng'-1 AND '$lng'+1 AND gym.id = gym_sport.gym_id AND sport.id = gym_sport.sport_id AND sport.name LIKE '%".$sports%."'";

Related

Is it possible to loop through each row of a table in a database

I'm trying to loop through each row of a table in a database, then once I'm on a particular row get the value of a certain column. Is this possible? I've done a couple Google searches but nothing really concrete. I try using the mysqli_fetch_array() function but when I do I get the results of a column. I want to target each row. The code I have so far gets me the "nid" column. That's not what I want. I want to iterate through each row.
<?php
$serverName = "localhost";
$username = "user1";
$password = "sp#99#1";
$databaseName = "developer_site";
// Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
echo "NID: ";
echo $row['nid'];
echo "<br/>";
}
?>
You can select rows by a certain condition with an SQL query alone and also select all columns.
SELECT * FROM node_revision where condition;
condition could be anything. For example another_row = 'something'.
But if, for some reason, you need to process the nid inside your php script to know if that row is the "particular" one you're searching, then you just select all the columns, or the ones you need.
$queryNodeRevision = "SELECT nid, col1, col2 FROM node_revision";
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
if (condiiton) {
echo "Particular: ".$row['nid']
." ".$row['col1']
." ".$row['col2'];
}
}
condition could be something like $row['nid'] == 123 for example.
Hope it helps.

Disease-Symptom relation in MySQL

I am making an electronic health system related to patient diagnosing in PHP and MySQL. I have made following tables in database with the following records:
Illness(illness_id(PK), illness_code,illness_name)
Symptom(symptom_id, illness_id(FK),symptom_name ).
Now, what I would like to do is that, I will write name of symptom in search bar and after clicking button, related diseases should be output. Could you tell me SQL query that will output appropriate diseases please?
Please try this. After you retrieve the symptom value from the search bar into a variable, say symptom_name_provided_in_search_bar, you can use that value in the below query
select illness_name
from illness a, symptom b
where a.illness_id = b.illness_id
and b.symptom_name = :symptom_name_provided_in_search_bar
For this to work you should create only one table illness with 2 rows:
illnessName and illnessSymptom. Note: This will only work if the symptom is written exactly as in the database.
<?php
$host = 'yourmysqlhost';
$user = 'yourmysqluser';
$pass = 'yourmysqlpassword';
$db = 'yourmysqldatabase';
$symptom = $_POST['symptom'];
$connect = mysqli_connect($host, $user, $pass, $db);
$sanitizedSymptom = mysqli_real_escape_string($connect, $symptom);
$query = mysqli_query($connect, "SELECT * FROM illness WHERE illnessSymptom = '".$sanitizedSymptom."'");
if(mysqli_num_rows($query) == 0)
{
echo '<p>No results...</p>';
}
else
{
while($row = mysqli_fetch_assoc($query))
{
echo '<h1>'.$row['illnessName'].'</h1>';
echo '<p>Symptom: '.$row['illnessSymptom'].'</p>';
echo '<br>';
}
}
?>
Edit:
To find a symptom that is approximately like the symptom in the database, the query should be like this:
$query = mysqli_query($connect, "SELECT * FROM illness WHERE illnessSymptom LIKE '%".$sanitizedSymptom."%'");

Why mysqli_num_rows always returns NULL?

I want to count the rows in the users table with specific name and pwd which should be 1 if existed.
but the result always return null(not 0),no matter whether the user existed or not.
I even change the query simple to "SELECT * FROM users", and it ended with the same result.
And I am pretty sure that the name of the DATABASE and TABLE are true,and the table is not empty!
By the way,why I have to use "#" symbol before "mysqli_query" in order to get rid of error?
thx!
enter code here
<?php
#$mysql_db_hostname = "localhost";
$mysql_db_hostname = "127.0.0.1";
$mysql_db_user = "root";
$mysql_db_password = "";
$mysql_db_database = "smartFSUsers";
$con = mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$name = $_GET["name"];
$password = $_GET["password"];
$query = "SELECT * FROM users WHERE name='$name' AND password='$password'";
$result =#mysqli_query($query,$con);
echo($result);
$row=#mysqli_num_rows($result);
echo"the row num is $row \n";
?>
RTM: http://php.net/mysqli_query
$result =#mysqli_query($query,$con);
You've got your parameters reversed. $con MUST come first:
$result = mysqli_query($con, $query) or die(mysqli_error());
If you had bothered adding error correction to your code, you'd have been told about this. But nope, you opted for # to hide all those error messages.

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;

Can not update records from one table into another

Hi I have a postcode database which contains postcodes and the lat and lon details, In another table i have a list of companies with postcodes and want to add the lat and lon details to matching postcodes, rather than use a join query etc. Below is the code i am using, i have used something similar before, but i just can not work out why this isn't working.
$host = "localhost";
$username = "";
$password = "";
$database = "";
mysql_connect( $host, $username, $password );
mysql_select_db( $database ) or die( "Unable to select database" );
$query = "SELECT * FROM postcodes";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$postcode = $row['postcode'];
$lat = $row['lat'];
$lon = $row['lon'];
$result = mysql_query("UPDATE companies SET lat ='$lat' and lng ='$lon'
WHERE postal_code = '$postcode'")
or die(mysql_error());
}
The error I am getting is: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/visitrac/public_html/postcode.php on line 15
if i move the closed bracket so it is before the update then the error goes but no information gets into the database, which i assume is because it is out of the loop. I have tried all sorts of things but nothing seems to work and so any nudges in the right direction would be appreciated.
Thanks
There's really no need for the loop through the postcode results. You can update all companies in a single SQL statement.
UPDATE companies c
INNER JOIN postcodes p
ON c.postal_code = p.postcode
SET c.lat = p.lat,
c.lng = p.lon
try this:
"UPDATE companies SET lat ='"+$lat+"' and lng ='"+$lon+"'
WHERE postal_code = '"+$postcode+"'"

Categories