How to get variables from MSQL query with WHERE IN clause - mysql

I have a couple of MySQL tables where I run a query on like this:
$sql = "
SELECT my_item
FROM t1
, t2
WHERE t1.id='$id'
AND t2.spec IN (208, 606, 645)
AND t1.spec = t2.spec
";
Note I am using the WHERE IN.
Next I run a query and use WHILE to try to get the results:
$retval = mysql_query($sql) or die('Query failed: ' . mysql_error());
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem = $row['my_item'];
echo "My item is $myitem<br />\n";
}
This prints three results, each with a different value for $myitem, based on the three options from the IN clause in the SELECT statement at the beginning.
How can I extract and store each of these three values in a separate variable each?
Thank you!

use join
SELECT my_item FROM t1 join t2
on t1.spec=t2.spec
WHERE t1.id='$id'
AND t2.spec IN (208, 606, 645)
or create array
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$myitem[] = $row['my_item'];
}
use this array likt that :-
foreach( $myitem as $myitems){
echo "My item is $myitems<br />\n";
}
or use indexing
echo "My item is $myitems[0]";

You can store the $row['my_item'] in an array.
Refer PHP arrays

Related

How to take values from one MySQl table, multiply them together, and put the results in another table

I have a table with 4 rows, I need to multiply col. 1 and 2 and put the results in col. 1 in the 2nd table. do the same with the other two cols' from table 1.
I'm sure its simple code. I just don't know MySQL
Get the values fetch the rows and insert again to the table 2:
$mysqli = new mysqli('127.0.0.1', 'tu_usuario', 'tu_contraseƱa', 'sakila');
if ($mysqli->connect_errno) {
echo "Errno: " . $mysqli->connect_errno . "\n";
echo "Error: " . $mysqli->connect_error . "\n";
exit;
}
$sql = "SELECT column1, column2 FROM table1";
if ($result = $mysqli->query($sql)) {
/* fetch object array */
while ($row = $result->fetch_row()){
$sql2 = "INSERT INTO table2 (col1) VALUES(".$row['column1']*$row['column2'].");";
$result = $mysqli->query($sql);
}
}
I didn't check if there is any error in theses code, it's just an example that shows the idea. I hope will be enough for you the explanation. If you still having doubts please answer again.

SQL QUERY SELECT INSIDE A FUNCTION

I am trying to work with a voting database system. I have a form to display all the candidates per candidate type. I'm still trying to to explore that. But this time, I want to try one candidate type, lets say for Chairperson, I want to display all candidate names for that type in the ballot form. However, there's an error with the line where i declare $query and made query statements, can somebody know what it is. I am very certain that my syntax is correct.
function returnAllFromTable($table) {
include 'connect.php';
$data = array ();
$query = 'SELECT * FROM ' . $table. 'WHERE candidateId=1'; //ERROR
$mysql_query = mysql_query ( $query, $conn );
if (! $mysql_query) {
die ( 'Go Back<br>Unable to retrieve data from table ' . $table );
} else {
while ( $row = mysql_fetch_array ( $mysql_query ) ) {
$data [] = $row;
}
}
return $data;
}
As #Darwin von Corax says, I sure that you have a problem between $table and WHERE
Your query:
$query = 'SELECT * FROM ' . $table. 'WHERE candidateId=1';
If $table = 'Chairperson';
You have:
'SELECT * FROM ChairpersonWHERE candidateId=1';
The your query should be:
$query = 'SELECT * FROM ' . $table. ' WHERE candidateId=1';

How to look for values in database and return an array of values

I'm looking for a way to search a MySQL database for specific values and put these in an array.
The contacts table has name,email,group,Phone...
I would like to search the database by group and return the email adresses in an array, separated by , (comma) to use further in my code.
What is the best way to do this?
$result = mysqli_query($link,"SELECT * FROM Contacts WHERE Group='Group 1'")
or die(mysqli_error());
...
while($row = mysqli_fetch_array( $result ))
{
array ( row->email,...)
}
Here you have different options beginning with:
Update your select query to only display the email, if you don't require the other fields this is the way to go
In your loop just add only the email field to the array
$dataArray[] = $row->email;
$result = mysqli_query($link,"SELECT email FROM Contacts WHERE Group='Group 1'")
or die(mysqli_error());
$emailArray = [];
while($row = mysqli_fetch_array( $result ))
{
array_push($emailArray,$row->email);
}
$responseEmail = implode(",", $emailArray);
Hope this will works!
I found the way of what I was trying to do. I needed a selectbox with values from the database.
....
$query = mysqli_query($link,"SELECT * FROM XXX WHERE category='$category' AND stelplaats='$stelplaats'");
echo '<td><select name ="collega" required>';
echo '<option value"">---</option>';
while ($row2 = mysqli_fetch_array( $query ))
{
echo '<option value =" '.$row2['id'].'"';
echo '>'.$row2['name'].'</option>';
}
echo '</select></td></tr>';
....

Mysql client ran out of memory

When i try to combine 3 tables having 50K records and write a MySQL select query:
select t1.c1,t2.c2 from table1 t1,table2 t2,table3 t3
where t3.column3='<value>' and t1.column1=t2.column1
and t2.column2=t3.column2
and t2.column2='<value1>' or t2.column2='<value2>'
This is the kind of the query which am writing to run
I get "mysql client ran out of memory"
Any help on how to overcome this will be highly appreciated.
Thanks
What client do you use? For mysql you can try running it with --quick option
Here's what I wrote to get around the memory limit. You'll have to modify the limits to match your environment. I'm breaking my results into a 500 per record batch and processing that and then looping into the next $records_per_batch.
<?php
// variables
$counter = 0;
$records_per_batch = 500;
$total_records = 0;
$app_root = "/var/run/consumers";
// mark the start time
system("/bin/touch $app_root/clean.last_start");
$link = mysqli_connect("localhost", "username", "password", "database") or die(mysqli_error());
// get the total amount of records to process
$sql = "SELECT COUNT(*) from table";
$result = mysqli_query($link, $sql) or die("couldn't execute sql: $sql" . mysql_error());
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$total_records = $row[0];
}
// iterate through the records at $records_per_batch at a time
$sql_template = "SELECT * FROM table order by table_id limit %s, %s";
while ($counter < $total_records) {
$sql = sprintf($sql_template,$counter,$records_per_batch);
$result = mysqli_query($link, $sql) or die("couldn't execute sql: $sql" . mysql_error());
if ($result) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
// do your work here.
}
}
} else {
print "hmm, no result\n";
exit;
}
$counter += $records_per_batch;
}
mysqli_close($link);
system("/bin/touch $app_root/clean.last_end");
?>
I know this post is old but I think it's worth mentioning that the or is probably causing an issue as well.
Here it is with some joins, and specifying the or for the t2 value only, which is what I think you want. This should limit your result set.
select t1.c1,t2.c2
from table1 t1
inner join table2 t2 on t2.column1=t1.column1
inner join table3 t3 pm t2.column2=t3.column2
where t3.column3='<value>'
and t2.column2 IN('<value1>','<value2>');
50K records is not too large to give you the type of problem described. You can try optimizing your tables by indexing on columns that join or limit such as t2.column1, t2.column2, etc.

How to select multiple records (row) from a column in mysql?

I want to display four (4) items'name from these id:
Can I do like this?
SELECT item_name from items WHERE item_id IN ('001', '012', '103', '500')
or
SELECT item_name from items WHERE item_id = '001' or item_id = '012' or item_id = '103' or item_id = '500'
IN RESPONSE TO ALL ANSWERS
Well, most of the answers said it works, but it does not really work. Here is my code:
$query = "SELECT `item_name` from items WHERE item_id IN('s001','a012','t103','p500')";
$result = mysql_query($query, $conn) or die (mysql_error());
$fetch = mysql_fetch_assoc($result) or die (mysql_error());
$itemsCollected = $fetch['item_name'];
echo $itemsCollected;
The item_id is alphanumeric.
You can do either one, but the IN query is much more efficient for this purpose for any large queries. I did some simple testing long ago that revealed it's about 10 times faster to use the IN construct for this. If you're asking if the syntax is correct then yes, it looks fine, other than missing semi-colons to complete the statement.
EDIT: It looks like the actual question you were asking was "why do these queries only return one value". Well, looking at the sample code you posted, the problem is here:
$fetch = mysql_fetch_assoc($result) or die (mysql_error());
$itemsCollected = $fetch['item_name'];
echo $itemsCollected;
You need to loop through and iterate until there are no more results to be fetched, as Pax pointed out. See the PHP manual page for mysql_fetch_assoc:
$sql = "SELECT item_name from items WHERE item_id IN('s001','a012')";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
Yes, both those should work fine. What's the actual problem you're seeing?
If, as you say, only one record is being returned, try:
select item_name from items order by item_id
and check the full output to ensure you have entries for 001, 012, 103 and 500.
If both those queries only return one row, I would suspect not.
If they all do exist, check the table definitions, it may be that the column is CHAR(4) and contains spaces for the others. You may have genuinely found a bug in MySQL but I doubt it.
After EDIT:
This is a perl/mysql problem, not an SQL one: mysql_fetch_array() returns only one row of the dataset at a time and advances a pointer to the next.
You need to do something like:
$query = "SELECT item_name from items WHERE item_id IN('s001','a012')";
$result = mysql_query($query, $conn) or die (mysql_error());
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["item_name"];
}
Your ID field must be set to auto increment, i guess. i had problems with that once and i changed the auto increment to int. in the IN field if you pass the parameters to match against the auto increment variable you get back only the first parameter, the remaining generates an error.
Use mysql_fetch_assoc to get the query and assign the values from mysql_fetch_assoc query into a an array. Simple as that
$i=0;
$fullArray = array();
$query = mysql_query("SELECT name FROM users WHERE id='111' OR id='112' OR id='113' ")or die(mysql_error());
while($row = mysql_fetch_assoc($query)){
foreach ($row as $value) {
$fullArray[$i] = $value;
}
$i++;
}
var_dump($fullArray);
echo $fullArray[0]."<br/>".$fullArray[1]."<br/>".$fullArray[2];`
You could also use the mysql_num_rows function to tell you how many rows your query retrieved and then use that result to increment a for loop. An example.
$num_rows=mysql_num_rows($query_results);
for ($i=0; $i <$num_rows ; $i++) {
$query_array[]=mysql_fetch_assoc($query_results);
}