PHP MYSQL Update several records in while loop - php

I have that simple php code:
$sql= 'SELECT ID, fb_postid, scheduled FROM `posts` WHERE clicks = "" AND fb_postid !="" AND scheduled < NOW() order by ID ASC LIMIT 10;';
$result = mysqli_query($link, $sql);
print_r($result);
while ($row = mysqli_fetch_assoc($result)) {
$clicks=fbcall($fbtoken, $row['fb_postid']);
$update="UPDATE `posts` SET `clicks`='".$clicks."' WHERE id='".$row['ID']."'";
$result = mysqli_query($link, $update);
print("POSTID: " . $row['fb_postid'] . " - Clicks: " . $clicks ."<br>");
};
The MYSQL SELECT gets 10 Lines from DB loops through the line in the While Loop, gets "clicks" from function fbcall and then should update all 10 lines with the values from "clicks" to the db. if i run the code without update i get 10 results printed but if i run with mysqli_update i just get 1 row updated. Anybody any Idea why?

You're using the $result variable to iterate through a list of rows from the first query.
But you're giving $result a new value within the loop, clearing whatever was there.
Just use two different variables, and you'll be fine. Try something like this:
$sql= 'SELECT ID, fb_postid, scheduled FROM `posts` WHERE clicks = "" AND fb_postid !="" AND scheduled < NOW() order by ID ASC LIMIT 10;';
$result = mysqli_query($link, $sql);
print_r($result);
while ($row = mysqli_fetch_assoc($result)) {
$clicks=fbcall($fbtoken, $row['fb_postid']);
$update="UPDATE `posts` SET `clicks`='".$clicks."' WHERE id='".$row['ID']."'";
$result2 = mysqli_query($link, $update);
print("POSTID: " . $row['fb_postid'] . " - Clicks: " . $clicks ."<br>");
};

Fixed it and built with prepared update statement:
$sql= 'SELECT ID, fb_postid, scheduled FROM `posts` WHERE clicks = "" AND fb_postid !="" AND scheduled < NOW() order by ID ASC LIMIT 10;';
$result = mysqli_query($link, $sql);
$qry = "UPDATE `posts` SET `clicks`=? WHERE id=?";
$stmt = mysqli_prepare ($link, $qry);
mysqli_stmt_bind_param ($stmt, 'ss',$clicks, $id);
while ($row = mysqli_fetch_assoc($result)) {
$clicks=fbcall($fbtoken, $row['fb_postid']);
$id=$row['ID'];
mysqli_stmt_execute($stmt);
print("POSTID: " . $row['fb_postid'] . " - Clicks: " . $clicks ."<br>");
};

Related

How to save the count() group by from mysql into a php variable

I need to save the count(activity_type) group by user_posted_to into a variable from mysql query
$query = "
SELECT user_posted_to, COUNT(*)
FROM activity_log_table
WHERE
post_type = 'discussion'
AND activity_type = 'Like' ";
$query .= "AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY AND activity_type <= CURRENT_DATE ";
$query .= "GROUP BY user_posted_to ORDER BY activity_timestamp DESC LIMIT 25";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
$user_posted_to = (int)$row['user_posted_to'];
$timestamp = time();
// I need to insert the count into this table for number_assert
$query2 = "INSERT INTO top_weekly (user_id, number_assert, timestamp) VALUES ($user_posted_to, $timestamp)";
$result2 = mysqli_query($connection, $query2);
$confirm_query2 = confirm_query($result2);
if($confirm_query2) {
echo "success query 2";
} else {
echo "failed query 2";
}
}
i expect to save the count() group by into a php variable and to be able to use it later on the page
You want to alias the « COUNT(*) » to something else, like « cnt ». Then you can access the column by name after fetching, as demonstrated below :
$query = "
SELECT
user_posted_to,
COUNT(*) as cnt
FROM activity_log_table
WHERE
post_type = 'discussion'
AND activity_type = 'Like'
AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY
AND activity_type <= CURRENT_DATE
GROUP BY user_posted_to
ORDER BY activity_timestamp DESC
LIMIT 25";
$result = mysqli_query($connection, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "user_posted_to: " . $row["user_posted_to"]. " - Count: " . $row["cnt"] . "<br>";
}
} else {
echo "0 results";
}
Add and AS label to the COUNT(*) then you will be able to readout that label in the row you get.
$query = "SELECT user_posted_to, COUNT(*) AS varCount FROM activity_log_table WHERE post_type = 'discussion' AND activity_type = 'Like' ";
$nummerOfCount = $row['varCount']

PHP Mysqli trigger a query one after other

I am trying to fetch first id from one table and later after all the ids are fetched i am trying to fetch number of all that id's.
My Problem is
As i want to select the value of first query completion result
I am unable to trigger second query after the first query is completed both are triggerid at a time
First Query
$query ="SELECT * FROM abc WHERE xyz='xyz' And Standard='xyz' ";
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
$ID = array();
while($row=mysqli_fetch_array($data)){
$ID[] = $row['ID'];
}
$IDall = "'" . implode("','", $ID) . "'";
Second Query
$query="SELECT mobno FROM euser WHERE UserId IN ($IDall)" ;
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
$mobiles = array();
while($row=mysqli_fetch_array($data)){
$mobiles[] = $row['MobileNum'];
}
$mobilesStr = implode(',', $mobiles);
echo $mobilesStr;
}
Try this
SELECT mobno FROM euser WHERE UserId IN (SELECT ID FROM abc WHERE xyz='xyz' And Standard='xyz');
You don't need 2 queries. Only 1 is enough
SELECT mobno FROM euser WHERE UserId IN (
SELECT ID FROM abc ...
)
Try this
$query ="SELECT * FROM abc WHERE xyz='xyz' And Standard='xyz' ";
$data=mysqli_query($mysqli,$query)or die(mysqli_error());
if(mysqli_num_rows($data) > 0) {
$ID = array();
while($row=mysqli_fetch_array($data)){
$ID[] = $row['ID'];
}
$IDall = "'" . implode("','", $ID) . "'";
$query2="SELECT mobno FROM euser WHERE UserId IN ($IDall)" ;
$data2=mysqli_query($mysqli,$query2)or die(mysqli_error());
$mobiles = array();
while($row=mysqli_fetch_array($data2)){
$mobiles[] = $row['MobileNum'];
}
$mobilesStr = implode(',', $mobiles);
echo $mobilesStr;
}
In this the second query will execute when the first query has a result.

Update rows of a SQL table

I have a table with a column called 'status'. The defaut value of 'status' is 0. I want to update the value to '1' after using it.
I basically want to check if the status is 0, if it is, do an operation and then change the value to 1.
Here is the code. All works perfectly except that the value of 0 is not changed to 1.
I am a novice so maybe is a very basic mistake :(
<?php
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$sql = "UPDATE summonerid SET status='1' WHERE status='0';"; // THIS IS THE PART THAT DOES NOT WORK WELL
}
}
}
?>
Any help would be highly appreciated
Try this.. you are not executing the sql statements
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$result1 = $conn->query($sql);
$sql = "UPDATE summonerid SET status='1' WHERE status='0';";
$result1 = $conn->query($sql);
}
}
}
?>

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.

How to execute PHP mysqli multi query by setting variables

I want to execute a multi query in PHP MySQL, and get the result. My queries are like this.
$sql1 = "set #uid:=(select chat_id from chat_notify where online=1 and engaged=0 limit 1);";
$sql1 .= "update chat_notify set engaged=1,emp_id=1 where chat_id=#uid;";
$sql1 .= " select #uid";
$sql = $mysqli->multi_query($sql1);
I want to get the result of the uid in php.
Change your code accordingly
$sql1 = "set #uid:=(select chat_id from chat_notify where online=1 and engaged=0 limit 1)";
$sql2 = "update chat_notify set engaged=1,emp_id=1 where chat_id=#uid";
$sql3 = "select #uid";
$mysqli->query($sql1);
$mysqli->query($sql2);
$res = $mysqli->query($sql3);
and then get your query result usual way

Categories