If I have a table in a MySQL DB, with fields id and position amung others.
Then in PHP I have an array like this:
Array
(
[0] => 1
[1] => 3
[2] => 8
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
Where the array key should map to the position and the array value should map to the id.
For example, If I made a call for every array value the first would be
UPDATE table SET position = 0 WHERE id = 1
Is there a way I could do all this in 1 call?
$string = "";
foreach($array as $k => $v)
$string .= "UPDATE table SET position = ".$v." WHERE id = ".$k.";";
mysql_query($string);
updating multiple records with different values for each record is possible, but it's not recommdned - it makes for an incredibly ugly query:
UPDATE table
SET position = CASE position
WHEN 0 THEN 1
WHEN 1 THEN 3
WHEN 2 THEN 8
etc...
Here we go a foreach solution :
$Array = array(0 => 1, 1 => 3);
if(count($Array) > 0){
foreach($Array as $Key => $Value)
// UPDATE table SET position = 1 WHERE id = 3 LIMIT 1
mysql_query('UPDATE table SET position = '.$Key.' WHERE id = '.$Value.' LIMIT 1;');
}
Problem : you can't do multiple update with MySQL ... yes, like Marc B said but it's very ugly.
Related
I have done the following to be able to get the results outside the loop (while):
$date_day = date('Y-m-d');
$stmt = $con->prepare("
SELECT MAX(l.id_logtrama) AS id_logtrama
, MAX(l.fechaHora) AS fechaHora
, l.idCliente
, l.idEquipo
, MAX(l.statusGlobal) AS statusGlobal
, COUNT(*) AS total
FROM logtrama l
JOIN equipo e
ON l.idEquipo = e.idEquipo
AND l.idCliente = e.idCliente
WHERE DATE(l.fechaHora)=?
GROUP
BY l.idCliente
, e.idEquipo
");
$stmt->bind_param("s", $date_day);
$stmt->execute();
$stmt->store_result();
$DataArray = [];
$stmt->bind_result(
$DataArray['id_logtrama'],
$DataArray['fechaHora'],
$DataArray['l.idCliente'],
$DataArray['l.idEquipo'],
$DataArray['statusGlobal'],
$DataArray['total']
);
while ($stmt->fetch()) {
$row = [];
foreach ($DataArray as $key => $val) {
$row[$key] = $val;
}
$array[] = $row;
}
print_r($array);
As a result, I get the following:
Array ( [0] =>
Array ( [id_logtrama] => 4
[fechaHora] => 2021-04-19 22:01:09.059800
[l.idCliente] => 20
[l.idEquipo] => 1
[statusGlobal] => 2
[total] => 1 )
[1] => Array (
[id_logtrama] => 3
[fechaHora] => 2021-04-19 22:01:05.520600
[l.idCliente] => 20
[l.idEquipo] => 8
[statusGlobal] => 2
[total] => 3 )
)
I need to be able to insert that data into another table for example alert_notify:
id_notify id_logtrama idCliente idEquipo alert_type count_notify notify_date
1 4 20 1 2 1 2021-04-19 22:01:09.059800
2 3 20 8 2 3 2021-04-19 22:01:05.520600
How can I achieve that goal?
I suggest you to make a single statement for SELECT and INSERT.
Doing something like this:
INSERT INTO alert_notify AS SELECT * FROM (
SELECT
MAX(l.id_logtrama) AS id_logtrama,
MAX(l.fechaHora) AS fechaHora,
l.idCliente,
l.idEquipo,
MAX(l.statusGlobal) AS statusGlobal,
COUNT(*) AS total
FROM logtrama l
JOIN equipo e
ON l.idEquipo=e.idEquipo
AND l.idCliente=e.idCliente
WHERE DATE(l.fechaHora)=?
GROUP BY l.idCliente, e.idEquipo
) AS t
WHERE NOT EXISTS (
SELECT 'x'
FROM alert_notify AS an
WHERE an.idCliente = t.idCliente
AND an.idEquipo = t.idEquipo
AND an.notify_date = t.fetchaHora
)
In this way only records without a corrispondence for idCliente, idEquipo, notify_date on alert_notify will be inserted.
PS: Explicit the line INTO alert_notify AS SELECT * with the fields list in the correct order, if the order of the defined field in alert_notify differs from the order of the fields returned by the SELECT
I'm creating multiple product variant's where user creates options for the product and and add values to options. after that when adding a product user select options for the product such as color, size or or for mobile ram, color, storage with fixed options quantity and price. I have created the database for it but i am unable to bind the variants related to product as per user input. As i m doing this in simplest form of php without oop concept but i am unable to do this
i have already tried using array. but unable to bind the options like :-
options
option_id option_name
1 Size
2 Color
3 Ram
4 Inch
5 Storage
option_values
value_id option_id value_name
1 1 S
2 1 M
3 1 L
4 2 Red
5 2 Black
6 3 4GB
7 3 8GB
8 5 500GB
products_variants
product_id option_id value_id sku_var
1 1 2 SKU_a1
1 1 2 SKU_a2
1 2 4 SKU_a1
1 2 5 SKU_a2
sku_variant_vlaues
quantity price sku_var
5 100 SKU_a1
8 120 SKU_a2
// Posting data using php
// FIXED Options
$product_quantity = isset($_POST['product_quantity ']) ? $_POST['product_quantity '] : '0';
$product_price = isset($_POST['product_price']) ? $_POST['product_price'] : '0';
/---------------------- OTHER VARIANT -------------------/
// this variable is ($all_options_filled) where user chooses which option to be added in product variant like color, size, ram, storage, inch, width etc.
in this variable all the input field name are stored as field1, field2, field3
foreach($all_options_filled as $aof_field_name){
if(!empty(trim($aof_field_name))){
$other_options = $con->query("SELECT `option_id`, `option_key`, `option_name` FROM `options` WHERE `option_key`='".$aof_field_name."' AND `status`='ACTIVE' ORDER BY `position` ASC LIMIT 1");
if($other_options->num_rows>0){
$row_other_options=mysqli_fetch_array($other_options);
$roo_option_id= $row_other_options['option_id'];
$roo_option_key = $row_other_options['option_key'];
$roo_option_name = $row_other_options['option_name'];
$multiple_option_name[] = isset($_POST[$roo_option_key]) ? $_POST[$roo_option_key] : ''; // array + multiple fields ## multiple array
$multiple_option_id[] = $roo_option_id; // all posted fields id's
}
}
}
/---------------------- OTHER VARIANT -------------------/
after inserting product data ->
getting the latest id of product as a ( $product_latest_id )
and sku id and sku title as per product as a ( $sku_latest_id , $sku_title )
below i am inserting the variants
if(!empty($multiple_option_name)){ // this variable came from other variants - those are created by user
//foreach($multiple_option_name as $one_multiple_option){
//var_dump($multiple_option_name);
for($i=0; $i<=sizeof($multiple_option_name)-1; $i++){
$multiple_option_name_1 = $multiple_option_name[$i];
$single_option_id = $multiple_option_id[$i];
if(!empty($multiple_option_name_1)){
//var_dump($one_multiple_option); echo "<br>";
if(!empty($multiple_option_name_1)){
//foreach($multiple_option_name_1 as $one_option_value){
//var_dump($one_option_value); echo "=> $single_option_id <br>";
for($j=0; $j<=sizeof($multiple_option_name_1)-1; $j++){
$one_option_value = $multiple_option_name_1[$j];
if(!empty($one_option_value)){
$get_one_option_value_id = $con->query("SELECT `value_id` FROM `option_values` WHERE `option_id`='".$single_option_id."' AND `value_name`='".$one_option_value."'");
if($get_one_option_value_id->num_rows>0){
list($g_option_value_id)=mysqli_fetch_array($get_one_option_value_id);
}else{
$goov_get_page_number=mysqli_query($con,"SELECT max(`position`) as position FROM `option_values` WHERE `option_id`='".$single_option_id."' ORDER BY `value_id` DESC LIMIT 1");
if($goov_get_page_number->num_rows==1){
$goov_row_pos = mysqli_fetch_array($goov_get_page_number);
$goov_position = $goov_row_pos['position']+1;
}else{
$goov_position = 1;
}
$create_one_option_value_id = $con->query("INSERT INTO `option_values`(`option_id`, `value_name`, `position`, `status`) VALUES
('".$single_option_id."', '".$one_option_value."', '".$goov_position."', 'ACTIVE')");
$get_latest_one_option_value_id = $con->query("SELECT `value_id` FROM `option_values`
WHERE `option_id`='".$single_option_id."' AND `value_name`='".$one_option_value."' AND `position`='".$goov_position."' AND `status`='ACTIVE'");
list($g_option_value_id)=mysqli_fetch_array($get_latest_one_option_value_id);
}
$sku_var = $sku_title."-$product_latest_id-$single_option_id-$g_option_value_id";
$insert_product_variant_values = $con->query("INSERT INTO `product_variant_values`(`product_id`, `option_id`, `value_id`, `value`, `sku_var`) VALUES
('".$product_latest_id."', '".$single_option_id."', '".$g_option_value_id."', '".$one_option_value."', '".$sku_var."')");
$p_quantity = $product_quantity[$j];
if($p_quantity>0){
$is_quantity_stock = 1;
}else{
$is_quantity_stock = 0;
}
$p_show_price = $show_price[$j];
$p_variant_currency = $admin_currency_code; // product currency
$p_price = $product_price[$j];
$p_variant_status = "ACTIVE";
$insert_sku_variant_vlaues = $con->query("INSERT INTO `sku_variant_vlaues`(`sku_id`, `product_id`, `sku_var`,
`stock`, `is_stock`, `show_price`, `currency`, `price`, `status`) VALUES ('".$sku_latest_id."', '".$product_latest_id."', '".$sku_var."',
'".$p_quantity."', '".$is_quantity_stock."', '".$p_show_price."', '".$p_variant_currency."', '".$p_price."', '".$p_variant_status."') ");
}
}
}
}
}
}
below is the table structure used for database:
product table -
product_id
product_name
Sku table-
sku_id
sku_title
product_id
options table -
option_id
option_key // used as input field name in front id
option_name
option values table-
value_id
option_id
value_name
product_variant_values table -
product_variant_value_id
product_id
option_id
value_id
sku_var -> // i am using this by adding (sku title, product_id, option_id and value_id) to match it unique to (sku_variant_vlaues table) so i can identify which option is used for which quantity and price
sku_variant_vlaues table -
id - primary key
sku_id
product_id
sku_var -> same sku value from (product_variant_values) table
quantity
price
$postData = array();
// $option_id you need to pass option value i create array so i print key you need to print object which contain the id of the option'
$option_array = [1 => 'Size' , 2=> 'Color'];
foreach ($option_array as $option_id => $value) { ?>
<input type="checkbox" name="option_type_id[<?php echo $option_id?>]" value="1">
<?php
}
$i = 0;
foreach ($option_array as $key => $option_type) {
$postData['option_type_id'][$key] = array();
$i++;
$array = $option_values[$key];
foreach ($array as $option_value_id => $value) {
$postData['option_type_id'][$key][] = $option_value_id;
?>
<input type="checkbox" name="option_type_id[<?php echo $key?>][option_values][]" value="<?php echo $option_value_id?>">
<?php }
}
$variants_data = array();
$lastInsertedProductId = 1;
$lastInsertedProductSKU = "SKU1";
foreach ($postData['option_type_id'] as $key => $value) {
foreach ($value as $option_id => $option_value) {
$variants_data[] = array(
'product_id' => $lastInsertedProductId,
'sku_var' => $lastInsertedProductSKU,
'option_id' => $key,
'option_value' => $option_value,
);
}
}
// it produce out put like this
Array
(
[0] => Array
(
[product_id] => 1
[sku_var] => SKU1
[option_id] => 1
[option_value] => 1
)
[1] => Array
(
[product_id] => 1
[sku_var] => SKU1
[option_id] => 1
[option_value] => 2
)
[2] => Array
(
[product_id] => 1
[sku_var] => SKU1
[option_id] => 2
[option_value] => 4
)
[3] => Array
(
[product_id] => 1
[sku_var] => SKU1
[option_id] => 2
[option_value] => 6
)
)
echo "<pre>";print_r($variants_data);die;
//So now you can simple check the output is matched according your database
when you post this inputs your functionality will work like this hope this will solve your problem
Here is my multi-dimensional array:
Array
(
[0] => Array
(
[H2H_Id] => T32
[Team1_Id] => T4
[Team1] => Juan Arraya - Max LePivert
[Team2_Id] => T205
[Team2] => Marco Grangeiro - Jeff Morneau
[Winners_Id] => T4
[MatchUps_Id] => M32
)
[1] => Array
(
[H2H_Id] => T39
[Team1_Id] => T205
[Team1] => Marco Grangeiro - Jeff Morneau
[Team2_Id] => T4
[Team2] => Juan Arraya - Max LePivert
[Winners_Id] => T205
[MatchUps_Id] => M32
)
[2] => Array
(
[H2H_Id] => T9
[Team1_Id] => T3
[Team1] => Marco Grangeiro - George Wilkinson
[Team2_Id] => T4
[Team2] => Juan Arraya - Max LePivert
[Winners_Id] => T4
[MatchUps_Id] => M9
)
)
I want the output to be:
Juan Arraya - Max LePivert 1 vs. 1 Marco Grangeiro - Jeff Morneau
Juan Arraya - Max LePivert 1 vs. 0 Marco Grangeiro - George Wilkinson
So basically, I want to display the different match ups separately by using MatchUps_Id and print the names of the teams Team1 and Team2. Based on the Winners_Id I want to add a counter to keep track of the wins per team per match up.
Keep in mind that these results are coming from user inputs which will make the multi-dimensional array different every time I request input from the user passed on by field1 and field2.
This is what I have so far in code:
$query2 = "SELECT HeadToHead.H2HNo H2H_Id, H2HTeam1Id Team1_Id, H2HTeam1 Team1, H2HTeam2Id Team2_Id, H2HTeam2 Team2, WinnersId Winners_Id, MatchUps.MatchUpsNo MatchUps_Id
FROM HeadToHead
JOIN MatchUps ON HeadToHead.MatchUpsNo=MatchUps.MatchUpsNo
WHERE ((H2HTeam1 LIKE '%$field1%' OR H2HTeam2 LIKE '%$field1%') AND (H2HTeam1 LIKE '%$field2%' OR H2HTeam2 LIKE '%$field2%'))";
$result2 = mysql_query($query2);
$num2 = mysql_num_rows($result2);
$arr2 = array();
if($num2 > 0) {
while($row2 = mysql_fetch_assoc($result2)) {
$arr2[] = $row2;
}
}
I get the desired results from the code above.
I think I have done a lot of research on this matter but what I am trying to accomplish seems to be different than what is out there.
Any help is much appreciated.
You can group the matchups together by 'MatchUps_Id' like this:
foreach ($arr2 as $match) {
// create some short ids to make the next part more readable
$id = $match['MatchUps_Id'];
$t1 = $match['Team1_Id'];
$t2= $match['Team2_Id'];
if (!isset($matchups[$id][$t1]['name'])) {
// initialize if this matchup has not yet been created
$matchups[$id][$t1]['name'] = $match['Team1'];
$matchups[$id][$t2]['name'] = $match['Team2'];
$matchups[$id][$t1]['wins'] = (int) ($match['Winners_Id'] == $match['Team1_Id']);
$matchups[$id][$t2]['wins'] = (int) ($match['Winners_Id'] == $match['Team2_Id']);
} else {
// increment wins if the matchup already exists
$matchups[$id][$t1]['wins'] += $match['Winners_Id'] == $match['Team1_Id'];
$matchups[$id][$t2]['wins'] += $match['Winners_Id'] == $match['Team2_Id'];
}
}
Using $t1 and $t2 as second-level keys allows you to increment the win count for respective teams without needing to know which one is which. The expression $match['Winners_Id'] == $match['Team1_Id'] returns a boolean, which will be implicitly cast to an integer 0 or 1 when used with +=, but must be explicitly cast using (int) when initializing.
After you have grouped your array and counted the wins, you can output the results like this:
foreach ($matchups as $matchup) {
list($a, $b) = array_values($matchup);
echo "$a[name] $a[wins] vs. $b[wins] $b[name]<br>";
}
The user can search for something using select and checkbox forms. The data is sent in GET variables.
I'm collected all the possible values in variables and putting it into an array:
$term_taxomony_ids_array = array($term_taxonomy_id_m, $term_taxonomy_id_l, $term_taxonomy_id_t_1, $term_taxonomy_id_t_2, $term_taxonomy_id_t_3, $term_taxonomy_id_t_4, $term_taxonomy_id_t_5, $term_taxonomy_id_t_6, $term_taxonomy_id_t_7, $term_taxonomy_id_t_8);
print_r($term_taxomony_ids_array); would then give
eg:
Array (
[0] => 12
[1] => 14
[2] =>
[3] =>
[4] => 9
[5] =>
[6] => 2
[7] =>
[8] =>
[9] =>
)
How would I make this array simpler but leaving out the empty results altogether (as suggested in a comment)?
I need to find the 'places' in the database who match all the criteria that was selected.
My database table is set up so I have two columns.
1. Object_id 2. term_taxonomy_id.
The term_taxonomy_id are the values in the array.
eg my table looks like this
Object id term_taxonomy_id
2 12
2 3
3 12
3 14
3 9
3 2
4 5
5 9
So only object_id '3' matches all the terms in the array - 12, 14, 9, 2
How would I run a query to find this result?
I'm using a mysql database, phpmyadmin and my site is built on wordpress.
Thanks
Basically:
SELECT objectID, COUNT(term_taxonomy_id) AS cnt
FROM yourtable
WHERE term_taxonomy_id IN (2, 9, 14, 12)
GROUP BY objectID
HAVING cnt = 4
find all the objectIDs that have one or more matching taxonomy IDs, but then return only the object IDs that have FOUR matching taxonomy IDs.
Use IN, Combined with COUNT() and having/GROUP.
$array = array_filter(array_unique($array));
$count = count($array);
$sql = "SELECT id, COUNT(*) FROM table WHERE field IN (" . implode(',', $array) . ") GROUP BY id HAVING COUNT(*) = " . $count;
The SQL might be a bit off (you might have to re-order having and group).
I am trying to build a website that will display the text in multiple languages.
I have a table 'text' with all the languages. If the text does not exist in the chosen language it has to display the default language.
query SELECT * FROM text WHERE TextId = 10
results in
Id TextId LanguageId Text
10 10 1 first name
13 10 2 名前
If I r_print this result I get something like this
Array ( [0] => Array ( [0] => 10 [Id] => 10 [1] => 10 [TextId] => 10 [2] => 1 [LanguageId] => 1 [3] => first name [Text] => first name )
[1] => Array ( [0] => 13 [Id] => 13 [1] => 10 [TextId] => 10 [2] => 2 [LanguageId] => 2 [3] => 名前 [Text] => 名前 ) )
How can I check that LanguageId 2 exist in this array ?
the problem is that it is possible that TextId 2 and Id 2 can also exist in this array.
Is this possible to do with in_array()?
Here is a function that can check if LanguageId equals a special value .
function isLanguageIdExists($yourArray , $LanguageId){
$exists=false;
foreach($yourArray as $array){
if(isset($array['LanguageId'])&& $array['LanguageId'] == $LanguageId){
$exists=true;break;
}
}
return $exists;
}
$exist = isLanguageIdExists($yourArray , 2);//return true or false
You can check by isset the key and match the value in php.
$dataArray = array(
0 => array(0 => 10 ,'Id' => 10, 1 => 10, 'TextId' => 10, 2 => 1, 'LanguageId' => 1),1 => array(0 => 10 ,'Id' => 10, 1 => 10, 'TextId' => 10, 2 => 1, 'LanguageId' => 1)
);
foreach($dataArray as $value) {
if(isset($value['LanguageId']) && $value['LanguageId'] == 2) {
echo 'language ID 2 is available';
}
}
Working Demo
After giving this some more thought I came up with a maybe not so elegant solution.
Instead of getting an array back I modified the SQL Query to give one row back with the default language (English) and a user selected language (Japanese).
It uses two left joins. This shows that I received (some) training in SQL but am really not at ease with multidimensional arrays.
Query
def_text = text in default language
usr_text = text in user chosen language
$table01 = "text";
$query="SELECT $table01.TextId,
text_def.Text as def_text,
text_usr.Text as usr_text
FROM $table01
LEFT JOIN $table01 as text_def ON $table01.TextId = text_def.TextId AND text_def.LanguageId = $_SESSION[default_language]
LEFT JOIN $table01 as text_usr ON $table01.TextId = text_usr.TextId AND text_usr.LanguageId = $_SESSION[language]
WHERE $table01.TextId=$mess;";
after getting back the results it is easy to check with isset() or empty() to see if the text is available in the user selected language