How to use an array in a WHERE sql clause? - php

i am trying to run the following php code:
$con = mysql_connect("localhost", "root", "") or die('connection not made');
$db = mysql_select_db('name', $con) or die('db not selected');
$query1 = "SELECT * FROM nodesensors WHERE NodeID=2";
$result1 = mysql_query($query1, $con);
$sensorids = mysql_fetch_array($result1);
$query2 = "SELECT SensorID, Variable FROM sensors WHERE SensorID IN($sensorids)";
$result2 = mysql_query($query2, $con) or die('query not made');
$sensors = mysql_fetch_array($result2);
echo $sensors;
where i want to get only those sensors that have a SensorID, which is also a value in the 'sensorids' array.
When i run the code i get the following:
Notice: Array to string conversion in C:\...\test.php on line 10
query not made
When i remove the "$" as follows:
$query2 = "SELECT SensorID, Variable FROM sensors WHERE SensorID IN(sensorids)";
the notice goes away, but still, the query is not made.
Is there any problem with the format of the 'sensorids' array?
Also, is 'echo' the right way to present the array or should i use another method?
Thanks a lot!

You don't have to use implode or anything, just combine your queries
SELECT SensorID, Variable FROM sensors WHERE SensorID IN
(
SELECT id FROM nodesensors WHERE NodeID=2
)
A note for all the implode based answers:
That will only work if they select only 1 column in their first query, they are doing SELECT * which results in a multi-dimensional array and doesn't contain only sensor ids and hence that will fail. See the updated answer by diEcho to read more about that.
And use a newer and safer extension for MySQL stuff
How can I prevent SQL injection in PHP?

I would suspect you can do this in 1 query, but I don't know your name of the id field, might be SensorID or something.
$query2 =
"SELECT SensorID, Variable
FROM sensors
WHERE SensorID IN (
SELECT id
FROM nodesensors
WHERE NodeID=2
)";
$result2 = mysql_query($query2, $con) or die('query not made');
$sensors = mysql_fetch_array($result2);
Alternatively:
$query2 =
"SELECT s.SensorID, s.Variable
FROM sensors AS s
INNER JOIN nodesensors ns ON ns.id = s.SensorID
WHERE ns.NodeID=2";
$result2 = mysql_query($query2, $con) or die('query not made');
$sensors = mysql_fetch_array($result2);

Try this and you are done,
Please don't use Select * but use the only column contain senserid
<?php
$con = mysql_connect("localhost", "root", "") or die('connection not made');
$db = mysql_select_db('name', $con) or die('db not selected');
$query1 = "SELECT * FROM nodesensors WHERE NodeID=2";
$result1 = mysql_query($query1, $con);
$sensorids = mysql_fetch_array($result1);
$query2 = "SELECT SensorID, Variable FROM sensors WHERE SensorID IN(".implode(',',$sensorids).")";
$result2 = mysql_query($query2, $con) or die('query not made');
$sensors = mysql_fetch_array($result2);
echo $sensors;
?>

fixes
SELECT * is wrong, select only sensorID column from nodesensors
SELECT sensor_column FROM nodesensors ...
Use implode with glue ',' before applying it to second query
$id_list = implode("','",$sensorids);
Mysql IN takes comma separated values
WHERE SensorID IN(" . $id_list . ")";

Use Implode
$sensorids = implode(',',$sensorids);
$query2 = "SELECT SensorID, Variable FROM sensors WHERE SensorID IN($sensorids)";

Related

PHP: use an array in a select where condition [duplicate]

This question already has answers here:
Passing an array to a query using a WHERE clause
(17 answers)
Closed 11 months ago.
I'm trying to query a MySQL database using an array but I'm having trouble!
I have a table called clients, I want to be able to select 'name' from all rows whose 'sector' column is equal to $sectorlink.
I then want to put all the names into an array so I can perform my next query: select all rows from another table whose 'client' column is equal to one of the names returned from the first query. I'm doing something wrong because it returns a fatal SQL error. I'm getting confused with all the variables!
$sectorlink and $connection are the only variables that are defined outside of this code
Any suggestions?
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
foreach($row AS $key => $value){$temp[] = '"'.$value.'"';}
$thelist = implode(",",$temp);
$query = "SELECT count(*) FROM studies WHERE client IN ($row) ORDER BY (date) desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
}
The second query should use $thelist not $row, and it should be outside of the while loop. The foreach loop is unnecessary when processing a single row. You can access the name in $row with a simple $row[0]. Something like this (untested):
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
$temp[] = '"'.$row[0].'"';
}
$thelist = implode(",",$temp);
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY (date) desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
Caution: Please be aware that your code is highly vulnerable to SQL injection attacks. It's fine for testing or internal development but if this code is going to be running the Fort Knox web site you're going to want to fix it up quite a bit. Just an FYI. :-)
Try This:
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while($row = mysql_fetch_array($clientresult)){
$client = $row['name'];
$query = "SELECT * FROM studies WHERE client='$client' ORDER BY date DESC";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
/* echo results here */
}
Couple of things. First you have an unnecessary loop there. Try:
while (list($name) = mysql_fetch_row($clientresult)) {
$temp[] = $name;
}
To build your temporary array.
Second, the parts of the IN clause are strings, so when you implode, you'll need to enclose each value in quotes:
$thelist = "'". implode("','", $temp) . "'";
Lastly, in your query you are passing $row to the IN clause, you should be passing $thelist:
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
So altogether:
$query1 = "SELECT name FROM clients WHERE sector = '$sectorlink'";
$clientresult = mysql_query($query1, $connection) or trigger_error("SQL", E_USER_ERROR);
while (list($name) = mysql_fetch_row($clientresult)) {
$temp[] = $name;
}
$thelist = "'". implode("','", $temp) . "'";
$query = "SELECT count(*) FROM studies WHERE client IN ($thelist) ORDER BY date desc";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);
I expect you'd be better off doing this in one query with a join:
$query = "SELECT COUNT(*) FROM `studies` INNER JOIN `clients` on studies.client = clients.name WHERE clients.sector = '$sectorlink' ORDER BY studies.date DESC";
$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);

MySQL using result of first query in second query

Is this possible. I have a MySQL query that returns a dynamic number of rows.
What I want to do is use the result from the returned rows as the column names in another query.
Example:
Result from first query:
SeqID4901
SeqID4902
SeqID4903
Normal second query:
mysql_select_db($database_Hp, $conn);
$query_Lookup_Hist = sprintf("SELECT * FROM Hist WHERE HeadID = %s", GetSQLValueString($colname_Hist, "text"));
$Lookup_Hist = mysql_query($query_Lookup_Hist , $conn) or die(mysql_error());
$row_Lookup_Hist = mysql_fetch_assoc($Lookup_Hist );
Using result of first query
mysql_select_db($database_Hp, $conn);
$query_Lookup_Hist = sprintf("SELECT SeqID4901, SeqID4902, SeqID4903 FROM Hist WHERE HeadID = %s", GetSQLValueString($colname_Hist, "text"));
$Lookup_Hist = mysql_query($query_Lookup_Hist , $conn) or die(mysql_error());
$row_Lookup_Hist = mysql_fetch_assoc($Lookup_Hist );
As I say, is this possible and where would I start.
Many trhanks in advance for your time.
If you dont want make this using just one query:
$columns = array();
$query = mysql_query("select column_with_column_names from your_table");
while($res = mysql_fetch_assoc($query))
$columns [] = $res['model'];
$result = mysql_query("SELECT ".implode(",",$columns)." FROM your_other_table");

MySQL AVG function returning 0

I'm using the code below to query the database.
mysql_query ("SELECT * FROM _$symbol ORDER BY date DESC;");
$_10day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 10;");
$_21day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 21;");
$_50day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 50;");
echo "$_10day\n";
echo "$_21day\n";
echo "$_50day\n";
mysql_query ("INSERT INTO _$symbol(_10day) VALUE ('$_10day');");
echo mysql_errno($sql) . ": " . mysql_error($sql). "\n";
I need to get the average of close from the database, and I'm using the AVG()function, then insert the return value into the database. The queries work in mysql however they do not work through the script. It does enter a value into the database, but it always enters 0. What am I doing wrong?
EDIT--solution found
$get10 = mysql_query ("SELECT AVG( close ) AS CloseAverage from ( SELECT close FROM _$symbol ORDER BY date DESC limit 10 ) sub1 ;");
$row = mysql_fetch_assoc($get10);
$_10day = $row['CloseAverage'];
if (!mysql_query ("UPDATE _$symbol SET _10day = $_10day, _21day = $_21day, _50day = $_50day, _100day = $_100day, _120day = $_120day, _150day = $_150day, _200day = $_200day, _240day = $_240day, _20dayVol = $_20dayVol, _50dayVol = $_50dayVol where date = '$date';"))
{
echo "Update query failed";
}
I was querying it incorrectly apparently it needed to be selected as a sub query, solution is above, it is working now.
Here's an example on how to manage multiple result-rows:
function connect()
{
$db = mysql_connect("localhost","username","password") or die("your error msg");
mysql_select_db("database_name");
return $db;
}
$db = connect();
$query = "SELECT value1 FROM my_table";
$result = mysql_query($query, $db);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
// This one will loop through the data in your output//
$outputValue = $row['value1'];
}
For inserting data:
// Continued from the state above //
$query = "INSERT INTO table_name (column1) VALUES (value1)";
$result = mysql_query($query, $db) or die(mysql_error());
$_10day is a mysql result, not a value. You can't just put a result into a query string and expect it to work.
You need to get the result data first, eg;
while($row = mysql_fetch_assoc($_10day)) {
$10day = $row['AVG(close)'];
}
Then you can execute your insert query;
mysql_query ("INSERT INTO _$symbol (_10day) VALUES ('$10day')");
Hope this helps.

The max value in a column with php

I have a MySql table "MyTable" with the column "order"
order
-----
3
4
2
1
I want to get the highest number. The sql statement works well inside MySql:
SELECT MAX(order) FROM MyTable"
But I do not know how to use it with php and echo it? Something like:
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$row = mysqli_fetch_array($result);
echo $row[0];
If you don't provide an alias to a MySQL function it will be shown as you've written it:
$row = mysqli_fetch_array($result);
echo $row['MAX(order)'];
What you can do is write something like:
$result = mysqli_query($con, "SELECT MAX(order) as 'max' FROM MyTable");
$row = mysqli_fetch_array($result);
echo $row['max'];
Which is using an alias.
Hope this helps!
Alternatively you can use ORDER BY DESC and Limit result to 1 this way you can easily get the maximum of an column .
$result=$con->query("SELECT order FROM MyTable ORDER BY order DESC LIMIT 1");
$row=mysqli_fetch_array($result);
echo $row['order'];
Or using MAX
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$row=mysqli_fetch_array($result);
echo $row[0];
This tutorial is directly from tizag, using the MySql Max function
MySQL Aggregate Functions - MAX()
// Make a MySQL Connection
$query = "SELECT type, MAX(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "The most expensive ". $row['type']. " is $" .$row['MAX(price)'];
echo "<br />";
}
Here's my answer:
$host = "localhost";
$username = "your_username";
$password = "your_password";
$db_name = "your_db_name";
$connection = mysql_connect($host, $username, $password) or die ("Error:: [1]");
mysql_select_db($db_name, $connection) or die ("Error:: [2]");
$query = "SELECT `order` FROM `MyTable` order by `order` desc";
$res = mysql_query($query, $connection);
$row = mysql_fetch_array($res);
print $row[0];
With this query , you always have the highest value of the give column.

PHP/MYSQL Different Trouble Selecting By Primary Key:

Due to some help from a recent post, I'm selecting a row by primary key, as follows:
$query ="SELECT * FROM Bowlers WHERE 'key' = '1'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result)or die(mysql_error());
For some reason, the third line of code dies every time, without error. It works fine using other keys, ie WHERE name = 'djs22'.
Any ideas?
You are using single quotes on the field name, you must use backticks.
not ', but `
try
$query ="SELECT * FROM Bowlers WHERE key = '1'";
or
$query ="SELECT * FROM `Bowlers` WHERE `key` = '1'";
instead of
$query ="SELECT * FROM Bowlers WHERE 'key' = '1'";
try using this
$query ="SELECT * FROM Bowlers WHERE `key` = '1'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result)or die(mysql_error());
I just replaced ' ' by .

Categories