I want to fetch each element of array in foreach loop.
Here in my code my array is displayed, I want to fetch this array element in if condition.
if (!empty($data[5])) {
$selectsql = "select value_id from catalog_product_entity_media_gallery where entity_id = '".$entity_id."'";
$selectsqlresult = $connection->query($selectsql);
$resultquery = $selectsqlresult->fetchAll();
print_r($resultquery);
if(!empty($resultquery['value_id']))
{
$imgpos = 2;
foreach($resultquery as $value)
{
$updatequery = "update catalog_product_entity_media_gallery_value set position = '".$imgpos."' where value_id = '".$value."' limit 1";
//$connection->query($updatequery);
echo $updatequery . "\n";
echo "Images Position - " . $imgpos ."\n\n"; $imgpos++;
}
}
}
I want to increase images position by 1 as per the array element.
Image position $imgpos is used in update query.
Please provide some guidance.
You could also use the key value in the foreach statement to get a incremented value:
if(!empty($resultquery['value_id']))
{
foreach($resultquery as $imgpos => $value)
{
$updatequery = "update catalog_product_entity_media_gallery_value set position = '".$imgpos."' where value_id = '".$value."' limit 1";
//$connection->query($updatequery);
echo $updatequery . "\n";
echo "Images Position - " . $imgpos ."\n\n"; $imgpos++;
}
}
Related
We have this MySQL query where we want to find the date_time and price_open from price table and update these two values into the price_datetime and price_open columns in comment table:
UPDATE comment AS fc
INNER JOIN price AS p
ON p.ticker_id = fc.ticker_id
AND p.date_time =
( SELECT pi.date_time
FROM price AS pi
WHERE pi.ticker_id = fc.ticker_id
AND pi.date_time >= fc.date_time
ORDER BY pi.date_time ASC
LIMIT 1
) SET
fc.price_datetime = p.date_time,
fc.price_open = p.price_open;
Which we converted to PHP+MySQL hoping for a more efficiency and much faster process:
<?php
ob_flush();
flush();
usleep(160);
$tickers = array();
$stmt = $mysqli->prepare("SELECT ticker_id, date_time FROM flaggedcomment order by ticker_id, date_time");
$stmt->execute(); //Execute prepared Query
$stmt->bind_result($tid, $dt);
$arr_index = 0;
while ($stmt->fetch() ) {
$tickers[$arr_index] = array();
$tickers[$arr_index]["id"] = $tid;
$tickers[$arr_index]["dt"] = $dt;
$arr_index++;
}
/* free result set */
$stmt->free_result();
$record_index = 0;
$flaggedcomment_index = 0;
$sql = "";
// get total tickers
$total_tickers = count($tickers);
echo "Total records: " . $total_tickers . "<br />";
foreach ($tickers as $ticker) { //fetch values
$stmt = $mysqli->prepare("SELECT price_open, date_time FROM price WHERE ticker_id =? AND date_time >=? ORDER BY date_time ASC LIMIT 1;");
$stmt->bind_param("is",$ticker["id"], $ticker["dt"]); // two params: one is integer, and other one is string
$stmt->execute(); //Execute prepared Query
$results = $stmt->get_result();
$myrow = $results->fetch_row();
$set_string = "SET";
// bind values
$price_open = $myrow[0];
$date_time = $myrow[1];
// set initial insert query value
$set_string .= " price_datetime='". $date_time ."'";
$set_string .= ", price_open=". $price_open;
$set_string .= " WHERE ticker_id=". $ticker["id"] ." AND date_time='" . $ticker["dt"] ."'";
if($set_string != ""){
$sql .= "UPDATE flaggedcomment ". $set_string . ";";
}
$idx = $record_index + 1;
if(($record_index + 1) % 100 == 0){
?>
<script>
$('#page-wrap > h1').html("Processing Ticker id #" + <?= $ticker["id"]; ?> + " - Record #" + <?= $idx; ?>);
</script>
<?php
ob_flush();
flush();
usleep(160);
}
$record_index++;
/* free result set */
$stmt->free_result();
} // end while fetch ticker id
$update_flaggedcomment_qry = "LOCK TABLES flaggedcomment WRITE; ". $sql . "UNLOCK TABLES; ";
echo $update_flaggedcomment_qry;
//echo "<br />";
if ($mysqli->multi_query($update_flaggedcomment_qry)) {
// nothing
} else {
echo "Error updating record: " . $mysqli->error . "<br />";
$mysqli->close();
exit;
}
echo "<span style='color:blue;'> <b> Done. </b> </span>";
ob_end_flush();
exit;
?>
Using the MySQL query, if there's no match of ticker_id and date_time from both tables, the fc.price_datetime and fc.price_open columns will show 0000-00-00 00:00:00 and 0.00 values. However, when executing the PHP code, instead of inserting the zero values, it will stop when it encounters its very first "no matching" of ticker_id and date_time and cannot continue. We've spent a long time figuring out on how to fix it, unfortunately, none of the ways we use can fix this.
Any help from the community is definitely much appreciated.
Thank you. :)
You do not check if there is a record returned from price . Hence your code just tries picking the first and second elements of the result array when that array is null. You then likely land up with a statement trying to assign blank to each of the price_datetime and price_open fields. With the price_datetime you have quotes around the empty value and mysql will probably cope with this, but for price_open you do not have quotes around the expected numeric value. Hence you will land up with an invalid update statement (some like the following):-
UPDATE flaggedcomment price_datetime='', price_open= WHERE ticker_id=123 AND date_time='2016-01-01 00:00:00';
As you are executing multiple SQL statements at once to do the updates, I expect that it won't execute any after the invalid statement.
A quick play with your code and the following should work. This checks the returned row and if one isn't found it just uses the default (zero like) values for the 2 fields you want to update.
<?php
ob_flush();
flush();
usleep(160);
$tickers = array();
$stmt = $mysqli->prepare("SELECT ticker_id, date_time FROM flaggedcomment order by ticker_id, date_time");
$stmt->execute(); //Execute prepared Query
$stmt->bind_result($tid, $dt);
$arr_index = 0;
while ($stmt->fetch() )
{
$tickers[$arr_index] = array();
$tickers[$arr_index]["id"] = $tid;
$tickers[$arr_index]["dt"] = $dt;
$arr_index++;
}
/* free result set */
$stmt->free_result();
$record_index = 0;
$flaggedcomment_index = 0;
$sql = "";
// get total tickers
$total_tickers = count($tickers);
echo "Total records: " . $total_tickers . "<br />";
foreach ($tickers as $ticker)
{ //fetch values
$stmt = $mysqli->prepare("SELECT price_open, date_time FROM price WHERE ticker_id =? AND date_time >=? ORDER BY date_time ASC LIMIT 1;");
$stmt->bind_param("is",$ticker["id"], $ticker["dt"]); // two params: one is integer, and other one is string
$stmt->execute(); //Execute prepared Query
$results = $stmt->get_result();
if ($myrow = $results->fetch_assoc())
{
$price_open = $myrow['price_open'];
$date_time = $myrow['date_time'];
}
else
{
$price_open = 0.00;
$date_time = "0000-00-00 00:00:00";
}
$sql .= "UPDATE flaggedcomment SET";
$sql .= " price_datetime='". $date_time ."'";
$sql .= ", price_open=".$price_open;
$sql .= " WHERE ticker_id=". $ticker["id"] ." AND date_time='" . $ticker["dt"] ."';";
$idx = $record_index++;
if(($record_index + 1) % 100 == 0)
{
?>
<script>
$('#page-wrap > h1').html("Processing Ticker id #" + <?= $ticker["id"]; ?> + " - Record #" + <?= $idx; ?>);
</script>
<?php
ob_flush();
flush();
usleep(160);
}
$record_index++;
/* free result set */
$stmt->free_result();
} // end while fetch ticker id
$update_flaggedcomment_qry = "LOCK TABLES flaggedcomment WRITE; ". $sql . "UNLOCK TABLES; ";
echo $update_flaggedcomment_qry;
//echo "<br />";
if ($mysqli->multi_query($update_flaggedcomment_qry)) {
// nothing
}
else
{
echo "Error updating record: " . $mysqli->error . "<br />";
$mysqli->close();
exit;
}
echo "<span style='color:blue;'> <b> Done. </b> </span>";
ob_end_flush();
exit;
?>
However I suspect that looping around the result of one query and doing another query for each row in php will be slower than a well constructed single update query.
If you do want to loop around the results like you are doing now it may be quicker to create a tmp table and insert the rows to that (as you can insert hundreds of rows with a single statement) and then update your flaggedcomment table with a single update statement that joins it to the tmp table
EDIT - If you can post the table declares and a bit of sample data I will have an attempt at doing it in a single SQL statement.
A first attempt (untested) would be:-
UPDATE comment AS fc
INNER JOIN price AS p
ON p.ticker_id = fc.ticker_id
INNER JOIN
(
SELECT *
FROM
(
SELECT fc.ticker_id,
MIN(pi.date_time) AS date_time
FROM comment AS fc
INNER JOIN price AS pi
ON pi.ticker_id = fc.ticker_id
AND pi.date_time >= fc.date_time
GROUP BY fc.ticker_id
) sub1
) sub0
ON p.ticker_id = sub0.ticker_id
AND p.date_time = sub0.date_time
SET fc.price_datetime = p.date_time,
fc.price_open = p.price_open;
This is using the extra seemingly redundant sub query to hopefully bypass a MySQL restriction on updating a table that is also used in a subquery.
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);
I have latest MySQL version (5.5) and this is the screenshot of groupid field
I didn't touch anything yet, but some cells are not ordered correctly like this
But if I click groupid name in the top, it will ordered correctly like this:
Below PHP code output is like first screenshot above, that are not ordered correctly. Please help how to make the output ordered correctly, like it is displayed in the second screenshot above,
Maybe add code like this : order by id asc, but which is the right place to add it below?
$group_ids = explode(" ", $options['groupchoice_ids']);
$groupsql = "SELECT id, title FROM " . TABLE_PREFIX . "thegroup WHERE";
$first = true;
foreach($group_ids as $value)
{
if (!$first)
{
$groupsql = $groupsql . " OR ";
}
else
{
$first = false;
}
$groupsql = $groupsql . " id = '" . $value . "' ";
}
$kh_optionsgroup = '<select name = "accounttype">';
$checksec = $db->query_read($groupsql);
if ($db->num_rows($checksec))
{
while ($lboard = $db->fetch_array($checksec))
{
$kh_optionsgroup = $kh_optionsgroup . "<option value
='" . $lboard['id'] . "'>" . $lboard['title'] . "</option>";
}
}
$verifystring = '$human_verify';
$kh_optionsgroup = $kh_optionsgroup . "</select>";
At the end of your query, you need to set an order, like so:
$groupsql="SELECT id, title FROM " . TABLE_PREFIX . "thegroup WHERE";
$first=true;
foreach($group_ids as $value){
if(!$first){
$groupsql = $groupsql." OR ";
}else{
$first = false;
}
$groupsql = $groupsql." id = '".$value."' ORDER BY groupid ASC";
}
ORDER BY id ASC
This will make the query return its results in ascending order from the groupid column. Simply change ASC to DESC if you want it to go descendinng (high->low).
So What I want to do is to echo 1 for the first row that is returned and two for the 2nd one and so one, Please I just don't know how to phrase this, I don't want to just count rows from mysql table, I want to give each row a number automatically and echo that number.
Please forgive my deprecated code.
$log = mysql_query("SELECT * FROM $table WHERE $columnid = '$id'") or die (mysql_error());
while($row = mysql_fetch_array($log)){
echo row['name'];
}
Lets assume that the above returns some names. so I want this.
1 : John
2 : Nancy
3 : Dave
I don't want to write those number.
Please take into account ORDER by rate DESC since I'm using that to descent the number by the biggest number of rate.
You could do:
$count = 1;
while($row = mysql_fetch_array($log)){
echo $count . ' ' . row['name'];
$count++;
}
Or:
echo '<ol>';
while($row = mysql_fetch_array($log)){
echo '<li>' . row['name'] . '</li>';
}
echo '</ol>';
$log = mysql_query("SELECT * FROM $table WHERE $columnid = '$id'") or die (mysql_error());
$c = 0
while($row = mysql_fetch_array($log)){
echo row['name'];
$c = $c + 1;
}
echo "Raw Count = ".$c
I have a table in the following structure...
ID USER_ID INTEREST
1 290 soccer
2 290 tennis
3 290 badminton
4 560 netball
I want to grab all values from the table where the user id is equal to the session user id and assign them as variables.
I have the following which works but displays the data very peculiarly..
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$interests[] = $row['interest'];
$interest1 = $interests[1];
$interest2 = $interests[2];
$interest3 = $interests[3];
print $interest1 . " - " . $interest2 . " - " . $interest3;
}
The above however outputs something along the lines of...
- - tennis - - tennis - badminton -
Can anybody see where I'm going wrong?
This should do what you need:
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = " . $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
while(list($interest) = mysql_fetch_array($result))
$interests[] = $interest;
print explode($interests, ' - ');
Think what happens to your loop at the first iteration:
$interest is an empty array
you fetch the first value and put it into $interest[0],
you fill $interest1 with the value that lies into $interest[1] (it is empty)
same for $interest2 and $interest3
you print ""." - ".""." - ".""
in the second run:
$interest is [0=>soccer]
you fetch the second value and put it into $interest[1],
you fill $interest1 with the value that lies into $interest[1] tennis
same for $interest2 and $interest3 (that are still empty)
you print "tennis"." - ".""." - ".""
and so on.
You need print the result when you exit the while loop (and the code is still flawed as
it don't get the value into the index 0 of the array).
An alternative should be:
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = "
. $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
// you fetch just a field, fetch_row will be sufficent
while($interest = mysql_fetch_row($result)) {
array_push($interests, $interest[0]);
}
echo implode(' - ', $interests);
$interests = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$interests[] = $row['interest'];
}
$int_count = count($interests);
$i=0;
foreach ($interests as $interest) {
$var = 'interest' . ($i + 1);
$$var = $interest;
$i++;
}
print $interest1 . " - " . $interest2 . " - " . $interest3;