Get 2 variables in sql and subtract them in PHP - php

I have multiple rows with data, some with data in mysql table kjoring and some that don't.
I am able to echo both $km1 and $km2 correctly, but I am unable to subtract them to find the result and echo $km0
$sqlq = "SELECT kjoring FROM oko WHERE kjoring!='' ORDER BY logdate DESC LIMIT 2";
if ( array_key_exists( 'field' , $out ) ) {
$sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}
$conn = new mysqli($servername, $username, $password, $dbname);
$result = mysqli_query( $conn , $sqlq );
if ( $result->num_rows > 0 ) {
while($row = mysqli_fetch_array($result)) {
$km1 = $row[0];
$km2 = $row[1];
$km0 = $km1 - $km2 ;
}
}
echo $km0 ;

First things first: Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
Next:
// $sqlq = 'SELECT ... FROM ... ORDER BY ... LIMIT'
if ( array_key_exists( 'field' , $out ) ) {
$sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}
When you add your WHERE conditions after the LIMIT there WILL be a syntax error returned by your DB. You need to add the WHERE condition after the FROM and in front of the ORDER BY.
$sqlq = 'SELECT ... FROM ... ';
if ( array_key_exists( 'field' , $out ) ) {
$sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}
$sqlq .= 'ORDER BY ... LIMIT ...';
Now to the 2 results:
while($row = mysqli_fetch_array($result)) {
$km1 = $row[0];
$km2 = $row[1];
When printing your row using var_dump() you will notice that there is only 1 column. You selected just one.
Using mysqli_fetch_all($result,MYSQLI_ASSOC); you will get an array containing both rows. Using this you can then do your computations.
PHP: mysqli_fetch_all()

Related

Joining two tables based off a condition SQL

I am building an android app that uses geo location. I am trying to improve my overall app to improve its smoothness while running. I am using volly to connect to a php page on my web sever where the php page can then access my phpmyadmin database. My php page for updating locations is a horrible mess and I was hoping it can be fixed with the right sql query.
Lets get down to it.
So I have a table named users
and a table named friends
In this particular example david is friends with mark and jack. Also to clarify mark and jack are friends with david.
What I need to do is Write a query if given a user ID say for example 3 that will produce a table of that person and his friends ID, cordsV1, cordsV2 without any duplicate IDs in the table.
I was able to get this to work with using loops and variables ect but as I said it is a horrible mess.
Here is my current all sql query attempt:
SELECT DISTINCT ID, cordsV1, cordsV2 FROM `friends`,`users` WHERE user_one_ID = 1 AND status = 1;
HOWEVER this just returns all of the user IDs from the user table. I am really bad with sql so if someone could point me in the right direction it would be much appreciated.
Here is my horrible mess of code if you were wondering:
<?php error_reporting(E_ALL | E_STRICT); ?>
<?php
$THIS_USER_ID = $_GET['THIS_USER_ID'];
try {
$one = 1;
$db = new PDO("");
$sql = "SELECT * FROM friends WHERE user_one_ID = '" . $THIS_USER_ID . "' AND status = '" . $one . "' OR user_two_ID = '" . $THIS_USER_ID . "' AND status = '" . $one . "'";
$rows = $db->query($sql)
->fetchAll(PDO::FETCH_ASSOC);
$printMe = [];
foreach($rows as $row){
$printMe[] = $row;
}
$jsonArr = json_encode($printMe);
$characters = json_decode($jsonArr, true);
// Getting the size of the sample array
$size = sizeof($characters);
$neg = -1;
$sql2 = "SELECT * FROM users WHERE ID = '" . $neg . "'";
$sql3 = "";
$sql4 = "";
for ($x = 0; $x < $size; $x++ ){
if ($characters[$x]['user_one_ID'] == $THIS_USER_ID && $characters[$x]['status'] == 1){
$hold = $characters[$x]['user_two_ID'];
$sql3 = $sql3 . " OR ID = '" . $hold . "'";
} else if($characters[$x]['user_two_ID'] == $THIS_USER_ID && $characters[$x]['status'] == 1) {
$hold = $characters[$x]['user_one_ID'];
$sql4 = $sql4 . " OR ID = '" . $hold . "'";
}
}
$sql5 = $sql2 . $sql3 . $sql4;
$sql7 = "SELECT * FROM users WHERE ID = '" . $THIS_USER_ID . "'";
$printMe2 = [];
$rows3 = $db->query($sql7)
->fetchAll(PDO::FETCH_ASSOC);
foreach($rows3 as $row3){
$printMe2[] = $row3;
}
$rows2 = $db->query($sql5)
->fetchAll(PDO::FETCH_ASSOC);
foreach($rows2 as $row2){
$printMe2[] = $row2;
}
$jsonArr2 = json_encode($printMe2);
echo $jsonArr2;
$db = null;
} catch(PDOException $ex) {
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
?>
Get the user-data
SELECT
*
FROM
users
WHERE ID = ?
Get the user-data of friends
SELECT
users.*
FROM
friends
JOIN
users ON users.ID = friends.user_two_ID
WHERE
friends.user_one_ID = ?
Better use prepared statements, or your app wont be alive very long due to SQL-Injections.
You also want to have a look at meaningful names.

Output of DISTINCT and <> from SQL Query issue

I am obtaining some values from an array and making a match against these values in an SQL Query.
The code for this is as follows:
foreach($files as $ex){
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$sql = 'SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` <> "' . $search . '" LIMIT 4';
}
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
The issue that I am having is that the <> seems not to be working.. I have even tried using the != operator, but still having the same issue.
The output of $search from the array are :
101m
102l
102m
103l
The output of SQL from the query is still:
101m
102l
102m
103l
Your code doesn't seem that logical, as you generate numerous SQL statements and then just execute the last one.
However I assume what you want to do is take a list of files, extract a string from each file name and then list all the pdb_code values from the table which are not already in the string.
If so something like this would do it. It takes each file name, extracts the sub string and escapes it, putting the result into an array. Then it builds one query, imploding the array to use in a NOT IN clause:-
<?php
$search_array = array();
foreach($files as $ex)
{
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$search_array[] = mysql_real_escape_string($search);
}
if (count($search_array) > 0)
{
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('" . implode("','", $search_array) . "') LIMIT 4";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
}
You have to use not in:
SELECT * FROM table_name WHERE column_name NOT IN(value1, value2...)
Try this:
$searchIds = implode(',',$search);
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('$searchIds') LIMIT 4";

Separate records with comma

I'm new to php and I want to separate the records with a comma.
Database:
the table in sql
I use this code to get the data:
<?php
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result))
{
echo "Test: " . $row["value"]. "<br>";
}
mysqli_close($con);
?>
It return twice as:
Test: Test
Test: Test1
I want to separate the records with a ',' like this:
Test: Test, Test1
Store your values in an array and than implode with ",". You will get the result:
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
$yourArr = array();
while($row = mysqli_fetch_array($result))
{
$yourArr[] = $row["value"];
//echo "Test: " . $row["value"]. "<br>";
}
echo "Test: ". implode(",",$yourArr);
You can do this entirely in MySQL using GROUP_CONCAT:
<?php
$id = get_the_ID();
$sql = "SELECT `parent_id`, GROUP_CONCAT(`value` SEPARATOR ', ') AS comma_separated_values
FROM tablename
WHERE `parent_id` = '$id'
GROUP BY `parent_id`";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result))
{
echo 'Test: ' . $row["comma_separated_values"]; // Test: test, test2
}
mysqli_close($con);
?>
You should change the "comma_separated_values" name to something more appropriate for your data.
In your particular case, you would not need the while() loop either as we're limiting the MySQL to a single row.
If you were to remove the WHEREparent_id= '$id' from the SQL query, then you could return the results of multiple parent_id values. For example:
while ($row = mysqli_fetch_array($result))
{
echo 'Parent ' . $row['parent_id'] .': ' . $row["comma_separated_values"] . '<br>';
}
Would return:
Parent 292: Test1, Test2
Parent 293: Test3, Test4
Parent 294: Test5, Test10, Test50
etc...
you can use update query for this
$query="Update tablename set value=CONCAT(value,',test1') where parentid='295'";
$result=mysqli_query($conn,$query);

How do I get columns from a joined table in PHP?

For a single table, I normally do something like this:
$length = 42;
$result = mysql_query ('SELECT * FROM table WHERE length = "' . $length . '"', $dbconn);
$rowsfound = mysql_num_rows ($result);
if ($rowsfound == 1) {
$row = mysql_fetch_array ($result);
$tableid = $row ['table_id'];
$tablecloth = $row ['tablecloth'];
$height = $row ['height'];
...
But how to I get the rows from a joined table like this:
$chairid = 123;
$result = mysql_query ('SELECT * FROM table,chair WHERE chair.id = "' . $chairid . '" AND table.table_id = chair.table_id', $dbconn);
$rowsfound = mysql_num_rows ($result);
if ($rowsfound == 1) {
$row = mysql_fetch_array ($result);
$tableid = $row ['table.table_id'];
$tablecloth = $row ['table.tablecloth'];
$height = $row ['table.height'];
...
This doesn't return any values in $table.tablecloth. What am I doing wrong?
do this with JOIN instead
SELECT * FROM table
INNER JOIN chair ON table.table_id = chair.table_id
WHERE chair.id = "' . $chairid . '"
The reason you are not getting any results is because your query is failing. table is a reserved word so you need to add back ticks around it as follows:
$result = mysql_query ('SELECT * FROM `table`,`chair` WHERE `chair`.id = "' . $chairid . '" AND `table`.table_id = `chair`.table_id', $dbconn);
You would had figured this out if you had proper error handling in place like following (note the or die():
$result = mysql_query ('SELECT * FROM `table`,`chair` WHERE `chair`.id = "' . $chairid . '" AND `table`.table_id = `chair`.table_id', $dbconn) or die(mysql_error())
Please refer to the list of reserved words here: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Apart from this, as Kim pointed out you also need to fix the extra closing parenthesis.
You would be better doing a proper JOIN like echo_Me suggested but this is the proper syntax for the way you are coding it.
$result = mysql_query ('SELECT table.*,chair.* FROM table,chair WHERE chair.id = "' . $chairid . '" AND table.table_id = chair.table_id', $dbconn);
Then
if ($rowsfound == 1) {
$row = mysql_fetch_array ($result);
$tableid = $row ['table_id'];
$tablecloth = $row ['tablecloth'];
$height = $row ['height'];
The results do not get returned with the table name in front of the column names. This can cause a problem if you have a column name with the same name in both tables.
I think you have extra closing parenthesis?? )
$tableid = $row ['table.table_id']);
$tablecloth = $row ['table.tablecloth']);
$height = $row ['table.height']);

retrieving a mysql query

I have written a mysql query and fetched the result as an assoc array using mysql_fetch_assoc().The query returns a list for two fields.I am looping through this field using through the result array and am extracting the value.how do i display the two fields since doing a plain echo is not working for me?The code which i have written is
Thanks in advance.
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
extract( $s );
echo $x . " - " . $y . "<br />";
}
I advise against using extract. it makes code very hard to follow.
I'd just do this:
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) ) {
echo $s['x'], ' - ', $s['y'], '<br/>';
}
mysql_fetch_assoc returns an array of mappings of key to value. As you didn't retrieve one and two from the database, $one and $two ($s['one'] and $s['two'] respectively) don't exist. Therefore do something like this, using the columns you selected as keys.
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
echo $s['x'] . " - " . $s['y'] . "<br />";
}
Or if you want to continue using extract (I don't recommend it, it can lead to some hard to track down bugs)
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
extract($s);
echo $x . " - " . $y . "<br />";
}
extract is a bad practice, furthermore your columns are probably called x and y and not one and two.
i suggest using the following:
echo htmlspecialchars($s['x']), ' - ', htmlspecialchars($s['y']);
According to your SELECT statement mysql_fetch_assoc() returns an array like array('x'=>something, 'y'=>something)and extract() would "translate" that to $x='something' and $y='something', not $one and $two.
Try
error_reporting(E_ALL);
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink) or die(mysql_error());
echo 'there are ', mysql_num_rows($result), " records in the result set\n";
while( false!==($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo $row['x'], ' ', $row['y'], "\n";
}

Categories