I need to select a whole column.
So my question is how do i get a whole column ?
$query = "SELECT * ";
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
I tried id=* but no luck ...
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.
EDIT:
function get_all_ids()
{
global $connection;
$query = "SELECT * ";
$query .= "FROM employees ";
$query_result = mysql_query ( $query , $connection );
confirm_query($query_result);
$query_result_array = mysql_fetch_assoc($query_result);
return $query_result_array;
}
i use this to print the array
$all_id = get_all_ids();
// preparing the table;
echo "<pre>";
print_r($table);
print_r($all_id);
echo "</pre>";
and this is the array
Array
(
[id] => 1
[department_id] => 1
[name] => jordan
[EGN] => 9108121544
[email] => testEmail
[address] => testAddress
[country] => testCounty
)
If there's more than one row in your result set, you need to keep fetching until all results are retrieved:
$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);
If you'd like to retrieve all ids in a single fetch, you could do:
$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);
$list_of_ids = explode(',', $row['id_list']);
WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.
If you want ALL the records then you dont need a WHERE condition at all.
Perhaps you mean the simple:
SELECT id
FROM employees
ORDER BY id ASC
If this gives you only one row, then either you have only one row or you are adding a LIMIT 1 or your PHP code does not loop through all the results but just shows the first one of them. Please add the PHP code.
If you want to select a single column. Then do not use "*", give the name of the columns name separated by comma and quoted with "`" (tick) for safety.
$query = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
Related
I have a MySQL database with varying rows and a specific column with arrays which I wish to combine and then remove the duplicates. For example, the following entries, row1 ([0] => 1) row2 ([0] => 2 [1] => 3) and row3 ([0] => 1 [1] => 2 [2] => 3). I need to combine them and remove duplicates like this:
rows ([0] => 1 [1] => 2 [2] => 3)
I have called the query from the database as follows and since the entries are stored by comma separation, (1,2,3), I used the explode function to get them in the format above.
$query2 = "SELECT * FROM samples_database WHERE order_id=$order_id AND micro_analysis<>'';";
$result2 = mysqli_query($conn, $query2);
$input = mysqli_fetch_array($result2);
$micro_analysis = $input['micro_analysis'];
$micro_analyses = explode(',', $micro_analysis);
print_r($result2);
From here I cannot seem to get the array from each separate row, it only gives a array result from the first row and thus affects my downstream results. How can I achieve this goal?
Store it as comma separated string and then explode it and make it unique. You can then use array_filter to remove any null or empty values
Also, you have missed looping the result set to fetch all values returned from the query.
Here' is the updated snippet,
$query2 = "SELECT * FROM samples_database WHERE order_id=$order_id AND micro_analysis<>'';";
$result2 = mysqli_query($conn, $query2);
$micro_analysis = '';
while($input = mysqli_fetch_array($result2))
{
$micro_analysis .= $input['micro_analysis'] . ',';
}
$micro_analysis_arr = array_filter(array_unique(explode(',', $micro_analysis)));
$query2 = "SELECT * FROM samples_database WHERE order_id=$order_id AND micro_analysis<>'';";
$result2 = mysqli_query($conn, $query2);
$micro_analysis = array();
while($input = mysqli_fetch_array($result2))
{
$micro_analysis[] = $input['micro_analysis'];
}
$micro_analysis_arr = array_unique($micro_analysis);
Hope this will help you
I have a php file that works up to a certain point but I need a bit of help on the loop for doing a MySQl Insert.
The following preforms a SELECT and then stores the Order ID for all records that have a order_status of 'S'. This works perfectly, printing each appropriate order ID.
I then push those affected ORder IDs to an array so that I can keep them stored for various functions.
//Query for checking all records in order_status
$orderCheck = "
SELECT
order_id,
order_status
FROM order_status
";
$result = mysqli_query($mysqlConn, $orderCheck);
$order_ids = array();
//loop results to gather order IDs and store them
while ($row = mysqli_fetch_array($result))
{
$order_id = $row['order_id'];
if ($row['order_status'] == "S")
{
array_push($order_ids, $order_id);
}
}
//print_r($order_ids);
//This does indeed print the correct order Ids
The following portion needs some work and I'm not quite sure what to do here. I'm iterating and foreach of those iterations I have an update, but i fear the syntax is incorrect on the update and I don't know if I'd need to do another array in here.
//This is where I'm stuck//
//Now I need to iterate through those orderIDs and update is_placement to 1, since it's a bit column, and udpate date_updated to curdate()
for($i=0; $i<count($order_id); $i++) {
$sql = "UPDATE order_status SET is_placement = '1' and date_updated = curdate() WHERE order_id = '$order_id'"; //I don't believe this syntax is correct
}
Basically, I need to preform a mysql update for each iteration of the previously stored $order_id array.
Any ideas or suggestions/guidance are much appreciated.
UPDATE:
output of the array:
[287] => 11605809
[288] => 11605817
[289] => 11605825
[290] => 11605863
[291] => 11605869
[292] => 11605870
[293] => 11605875
[294] => 12605471
[295] => 12605643
[296] => 12605715
[297] => 12605778
[298] => 12605817
It makes little sense to ask MySQL for all the orders, and then select manually those with status S.
Better:
// Select only orders in status S.
$orderCheck = "SELECT order_id FROM order_status WHERE order_status = 'S';"
$result = mysqli_query($mysqlConn, $orderCheck);
$order_ids = array();
while ($row = mysqli_fetch_array($result)) {
$order_ids[] = $row['order_id'];
}
Now you want to update those records. If you do it one by one, you do:
foreach ($order_ids as $order_id) {
$sql = "UPDATE order_status SET is_placement = 1, date_updated = DATE(NOW()) WHERE order_id = '$order_id';";
// EXECUTE
}
A faster way would be (I'm not adding quotes, assuming that order ids are numeric, but if they aren't things get a bit more complicated) to put all order ids together and use the IN syntax:
$bunchOfOrders = implode(',', $order_ids);
$singleQuery = "UPDATE order_status SET is_placement = 1, date_updated = DATE(NOW()) WHERE order_id IN ({$bunchOfOrders})";
But you could have done all this in MySQL too:
$orderUpdate = "UPDATE order_status SET is_placement = 1, date_updated = NOW() WHERE order_status = 'S';"
$result = mysqli_query($mysqlConn, $orderUpdate);
Since the above does not change the order status from S, you can then also run $orderCheck and retrieve the order-ids involved, if necessary.
To be sure that nothing untoward happens, I would also wrap the whole operation inside a transaction.
Another twist
What if we have to run a series of different modifications depending on some condition (mutually exclusive, of course)?
We can do this with a map, as long as we use deterministic functions and no modification changes the conditions below (so, you can't change order_status in any of the "recipes", or it would influence those that come after):
$todo = array(
"order_status='S'" => "is_placement = 1, date_updated = DATE(NOW())",
"order_status='K'" => "is_placement = 2, date_updated = DATE(NOW())",
"order_status='L'" => "owner='NOBODY'",
"o_s='X' AND a=12" => "note='A random condition'",
// We can also supply a "what to do if none of the above":
"DEFAULT" => "note='THIS RECORD DOES NOT MATCH'",
);
$else = array();
foreach ($todo as $when => $then) {
if ('DEFAULT' !== $when) {
$else[] = "({$when})";
} else {
// "ELSE" means when no other condition is matched.
// i.e. NOT when1 AND NOT when2 AND NOT when3...
// which is equivalent to NOT ( when1 OR when2 ... )
$when = "NOT (" . implode(' OR ', $else) . ")";
}
$sql = "UPDATE order_status SET {$then} WHERE {$when};";
// Execute $sql.
}
What you could use is a foreach() statement:
foreach($order_ids AS $order_id) {
$sql = "UPDATE order_status SET is_placement = '1', date_updated = curdate() WHERE order_id = $order_id";
// execute the query here
}
While you are using information from data contained in your table you should consider learning about prepared statements MySQLi
I would change the initial query so you don't have to loop through anything more than once.
Try this:
//Query for checking all records in order_status
$orderCheck = "
SELECT
order_id,
order_status
FROM order_status
WHERE order_status = 'S'
";
$result = mysqli_query($mysqlConn, $orderCheck);
$order_ids = array();
//loop results to gather order IDs and store them
while ($row = mysqli_fetch_row($result))
{
$sql = "UPDATE order_status SET is_placement = '1' and date_updated = curdate() WHERE order_id = '$row[0]'";
}
This is the $_POST array from my form.
Array ( [prescribedid] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 9 [4] => 13 )
I want to create a select for any of items in the Array. I have written this, which produces the proper SELECT, but the if() to eliminate a trailing OR makes it clunky.
$query = "SELECT * ";
$query .= "FROM prescribed WHERE ";
for($i=0; $i<count($_POST["prescribedid"]); $i++) {
$query .= "prescribedid={$_POST['prescribedid'][$i]} ";
if($i < (count($_POST["prescribedid"])-1)) {
$query .= "OR ";
}
}
It produces this:
SELECT * FROM prescribed WHERE prescribedid=1 OR prescribedid=2 OR prescribedid=3 OR prescribedid=9 OR prescribedid=13
Is there another way to group the SELECTS or write the FOR() to make it cleaner, i.e. without the last IF().
$values=implode(",",$_POST["prescribedid"]);
$query = "SELECT * FROM prescribed WHERE prescribedid IN ($values)";
Sanitization is on you :)
Hi You can Use In condition. use imploade function to find comma seoarated values
$data = array('prescribedid'=>array(1,2,3,9,14));
$query = 'SELECT * FROM prescribed WHERE prescribedid IN (';
$query .= implode(',',$data['prescribedid']).')';
echo $query ;
Output
SELECT * FROM prescribed WHERE prescribedid IN (1,2,3,9,14)
Use MySQL IN clause
$ids = implode(",",$_POST["prescribedid"]);
$query = "SELECT * FROM prescribed WHERE prescribedid IN ($ids)";
You can simply use IN clause here.
Refer to MySQL IN clause
$query = "SELECT * FROM prescribed WHERE prescribedid IN ".implode(',', $_POST["prescribedid"]);
I'm trying to get the total number of product sales in each category, although the database structure being used doesn't really seem to lend itself to this.
I've gotten it to the point where I have the IDs of products (it's own table) in a category (another table) that have only been purchased (still another table). So looping through the category, I choose the IDs in the orders table and try to count the rows. I end up with the item count per item, but any way I try to merge and count them up them doesn't work.
$SQL = "SELECT * from PRODUCTS WHERE CATEGORY LIKE '%-$thiscat-%' AND STATUS = 'Active' AND STOREITEM = 'Yes' AND ID IN ($item_ids)";
$result = mysql_query( $SQL );
while( $row = mysql_fetch_array( $result ) ) {
$sql_active_accounts = "SELECT count(ID) FROM ORDERS WHERE ITEM_NUMBER ='$row[ID]'";
$res_active_accounts = mysql_query($sql_active_accounts);
while($row_active_accounts = mysql_fetch_row($res_active_accounts)){
print_r($row_active_accounts);
}
};
An example that print_r gives for a specific category that only had 3 items sell, but some items sold more than once:
Array ( [0] => 2 ) Array ( [0] => 3 ) Array ( [0] => 1 )
This is correct in that three items sold, sold those number of times.
And array_sum doesn't work on this. I can't seem to do anything to get those numbers to add up. I'm trying to count just specific rows and really don't care about the data in them for the final result.
I understand SQL calls within loops are a bad idea, but this is an admin area script that won't be run often.
$SQL = "SELECT * from PRODUCTS WHERE CATEGORY LIKE '%-$thiscat-%' AND STATUS = 'Active' AND STOREITEM = 'Yes' AND ID IN ($item_ids)";
$result = mysql_query( $SQL ); while( $row = mysql_fetch_array( $result ) ) {
$sql_active_accounts = "SELECT count(ID) FROM ORDERS WHERE ITEM_NUMBER ='$row[ID]'";
$res_active_accounts = mysql_query($sql_active_accounts);
$int_total = 0;
while($row_active_accounts = mysql_fetch_row($res_active_accounts) {
foreach($row_active_accounts as $i)
$int_total += $i;
}
// Use $int_total for total value
Some like this should do the trick for your if I understand you correctly.
Try this
$query = mysql_query("select distinct(pgroup) from test") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo $row['pgroup']."=>";
$query1="SELECT count(*),pname FROM `test` where pgroup='$row[pgroup]' group by pname ";
$result1=mysql_query($query1) or die(mysql_error());
$rows1=mysql_num_rows($result1);
while($row_sub=mysql_fetch_array($result1)) {
$query2 = "select * from test where pname = '".$row_sub['pname']."'";
$res2=mysql_query($query2) or die(mysql_error().'errror here');
$row2 = mysql_num_rows($res2);
echo $row_sub['pname']."=".$row2."<br/>";
}
}
I have the following table structure. One table EQUITIES and a table for each row in this table.
EQUITIES table:
id instrument
and tables for every instrument with are all similar to this:
Tables named like EE5367126893 (various names and the names are stored in equities table).
EE5367126893
id chg
EDIT:
My code is BAD. It somehow gets me wrong results and i can't seem to find an error.
<?
//CREATION OF TOP MOVERS
include('connect.php');
$sql = "SELECT * FROM equities";
$result = mysql_query($sql) or die(mysql_error());
$instruments = array();
while ($row = mysql_fetch_array($result)) {
array_push($instruments, $row["instrument"]);
}
$i=0;
foreach($instruments as $instrument) {
$sqlx .= "(SELECT id, chg, vol, '$instrument' as name FROM ".$instrument." ORDER BY id DESC LIMIT 1)";
if ($i<count($instruments)-1){
$sqlx .= " UNION ";
$i++;
}
}
$gsql = $sqlx;
$lsql = $sqlx;
$vsql = $sqlx;
//Gainers
$gsql .= " ORDER BY chg DESC LIMIT 3";
$gresult = mysql_query($gsql) or die(mysql_error());
while ($grow = mysql_fetch_array($gresult)) {
$g[$grow['name']] = $grow['chg'];;
}
print_r($g);
//losers
$lsql .= " ORDER BY chg ASC LIMIT 3";
$lresult = mysql_query($lsql) or die(mysql_error());
while ($lrow = mysql_fetch_array($lresult)) {
$l[$lrow['name']] = $lrow['chg'];;
}
print_r($l);
//most volume
$vsql .= " ORDER BY vol DESC LIMIT 3";
$vresult = mysql_query($vsql) or die(mysql_error());
while ($vrow = mysql_fetch_array($vresult)) {
$v[$vrow['name']] = $vrow['vol'];;
}
print_r($v);
?>
It got me results:
Array
(
[LV0057869] => 0.68
[EE310054309] => 0.00
[EE3100034553] => -5.03
)
Array
(
[LV0054359] => -0.84
[LT0000543337] => -3.83
[LT00453127375] => -4.03
)
Array
(
[EE310054334653] => 791
[EE3100003609] => 58538
[LT000543337] => 33240
)
Its pretty obvious that I'm not getting the the highest, lowest or values with most vol (as -0.84>-5.03).It looks like random values got locked with this query. Where's the catch? Im pretty sure theres something bad with my sql query...
You can add name to select
SELECT id, chg, 'table_name or instrument_name' as inst_name from ...
Example:
$sqlx .= "(SELECT id, chg, '$instrument' as name FROM ".$instrument." ORDER BY id DESC LIMIT 1)";
It seems that vol has got VARCHAR type and rows are sorted by chars not by integers.
Could you provide your table scheme?