I've created a script to run on my database at five minute intervals as a cron job. It's not a well written piece of code, but it's done quickly and should do the job for now.
I'm executing a WHILE loop to execute multiple if statements which in turn have multiple SQL statements within them. Problem is, it's only iterating the WHILE loop once and then stops and i'm not entirely sure why. Code is as below:
<?php
require_once('config.php');
$hashtags = mysql_query("SELECT id, hashtag FROM hashtags WHERE enabled = '1'") or die(mysql_error());
while($row = mysql_fetch_array($hashtags))
{
$hashtag_id = $row['id'];
$hashtag = $row['hashtag'];
//Get id and latest_tweet_id from report log
$latest_report_tweet_id_query = mysql_query("SELECT id, latest_tweet_id FROM reports_log WHERE name = 'post_count' AND hashtag_id = '".$hashtag_id."' LIMIT 1") or die(mysql_error());
if (mysql_num_rows($latest_report_tweet_id_query) == 0) {
$new_report_tweet_id_query = mysql_fetch_array(mysql_query("SELECT tweet_id FROM tweet_tags WHERE tag = '".$hashtag."' ORDER by tweet_id desc LIMIT 1")) or die(mysql_error());
$new_report_tweet_id = $new_report_tweet_id_query['tweet_id'];
$post_count_query = mysql_fetch_array(mysql_query("SELECT count(tweet_id) as tweet_count FROM tweet_tags WHERE tag = '".$hashtag."' AND tweet_id <= '".$new_report_tweet_id."'")) or die(mysql_error());
$post_count = $post_count_query['tweet_count'];
if(mysql_query("INSERT INTO post_count_reports (timestamp, hashtag_id, post_count, latest_tweet_id) VALUES ('".date("Y-m-d H:i:s")."', '".$hashtag_id."', '".$post_count."', '".$new_report_tweet_id."')"))
{
//Get just created id of the report
$report_id_query = mysql_fetch_array(mysql_query("SELECT id FROM post_count_reports WHERE hashtag_id = '".$hashtag_id."' AND latest_tweet_id = '".$new_report_tweet_id."'")) or die(mysql_error());
$report_id = $report_id_query['id'];
if(mysql_query("INSERT INTO reports_log (timestamp, hashtag_id, name, latest_tweet_id, latest_report_id) VALUES ('".date('Y-m-d H:i:s')."', '".$hashtag_id."', 'post_count', '".$new_report_tweet_id."', '".$report_id."')"))
{
echo "Successfully created report! NEW";
}
else {
echo "Failed updating report log! NEW";
}
}
else
{
echo "Failed making report! NEW";
}
}
else {
//Set the latest report id
$latest_report_tweet_id_array = mysql_fetch_array($latest_report_tweet_id_query);
$latest_report_log_id = $latest_report_tweet_id_array['id'];
$latest_report_tweet_id = $latest_report_tweet_id_array['latest_tweet_id'];
//Query to get the latest tweet_id in the database
$new_report_tweet_id_query = mysql_fetch_array(mysql_query("SELECT tweet_id FROM tweet_tags WHERE tag = '".$hashtag."' ORDER by tweet_id desc LIMIT 1")) or die(mysql_error());
$new_report_tweet_id = $new_report_tweet_id_query['tweet_id'];
//Query to get the new post count from database
$new_post_count_query = mysql_fetch_array(mysql_query("SELECT count(tweet_id) as tweet_count FROM tweet_tags WHERE tag = '".$hashtag."' AND tweet_id > '".$latest_report_tweet_id."' AND tweet_id <= '".$new_report_tweet_id."'")) or die(mysql_error());
$new_post_count = $new_post_count_query['tweet_count'];
$old_post_count_query = mysql_fetch_array(mysql_query("SELECT id, post_count FROM post_count_reports ORDER by timestamp desc LIMIT 1")) or die(mysql_error());
$old_post_count = $old_post_count_query['post_count'];
$post_count = $old_post_count + $new_post_count;
if(mysql_query("INSERT INTO post_count_reports (timestamp, hashtag_id, post_count, latest_tweet_id) VALUES ('".date('Y-m-d H:i:s')."', '".$hashtag_id."', '".$post_count."', '".$new_report_tweet_id."')"))
{
//Get just created id of the report
$report_id_query = mysql_fetch_array(mysql_query("SELECT id FROM post_count_reports WHERE hashtag_id = '".$hashtag_id."' AND latest_tweet_id = '".$new_report_tweet_id."' ORDER by timestamp desc LIMIT 1")) or die(mysql_error());
$report_id = $report_id_query['id'];
if(mysql_query("UPDATE reports_log SET id = '".$latest_report_log_id."', timestamp = '".date('Y-m-d H:i:s')."', latest_tweet_id = '".$new_report_tweet_id."', latest_report_id = '".$report_id."' WHERE name = 'post_count'"))
{
echo "Successfully created report!";
}
else {
echo "Failed updating report log!";
}
}
else
{
echo "Failed making report!";
}
}
}
?>
Massive error on my part, turns out whilst there were three hashtags in the hashtags table there were only rows with one of the hashtags in the tweet_tags table. Wasted a few hours on this one.
Moral of the story, always log and check for errors!
Related
Based on my codes, i need to restrict the insertion of the data by 3, i mean is like after the insertion of 3 data row, it will be restricted from inserting in data. Is that possible? For more information, is like the borrow inserting 3 times, then it cannot be inserted anymore. Is there anyway to do so? I am still learning php by the way, thank you.
if(isset($_POST['selector']))
$id=$_POST['selector'];
else
$id = '';
$member_id = $_POST['member_id'];
$due_date = $_POST['due_date'];
$isbn = $_POST['due_date'];
if ($id == '' ){
//header("location: borrow.php");
if(isset($_POST['isbn'])){
$isbn = $_POST['isbn'];
$query = mysql_query("select book_id from book WHERE isbn = '$isbn'")or die(mysql_error());
$count = mysql_num_rows($query);
if($count > 0){
$row = mysql_fetch_array($query);
$bookid = $row['book_id'];
$date = date('Y-m-d');
}
mysql_query("insert into borrow (member_id,book_id,date_borrow,due_date) values ('$member_id','$bookid','$date','$due_date')")or die(mysql_error());
}
else{
header("location: borrow.php");
}
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
mysql_query("insert borrowdetails (book_id,borrow_id,borrow_status)
values('$id[$i]','$borrow_id','pending')")or die(mysql_error());
}
header("location: borrow.php");
}
You just have to count number of user row before to make a new insert :
$query = mysql_query("SELECT COUNT(*) AS count FROM borrow WHERE member_id = '".$member_id."'");
$row = mysql_fetch_assoc($query);
if ( $row['count'] >= 3 )
echo('Max insert');
Also, check this : Why shouldn't I use mysql_* functions in PHP?
I'm not sure I understand you correctly.
You can restrict the number of rows returned by SELECT query using the LIMIT clause.
Make sure you either put an ORDER BY clause in there or determine that you don't care 'which' 3 rows will get inserted.
See here:
http://dev.mysql.com/doc/refman/5.0/en/select.html
I can see in my logcat that the $check query is only running once, when it should be running once for every result of the $result query, which is 6. I've been troubleshooting this for hours and I just can't figure out why it's not working properly.
Is there an obvious reason why $check is only running once?
$result = mysql_query("SELECT * FROM `posts` WHERE facebook_id = $fbid ORDER BY id DESC") or die(mysql_error());
while ($row1 = mysql_fetch_array($result))
{
$mytime = $row1['time'];
$mylat = $row1['latitude'];
$mylon = $row1['longitude'];
$mypostid = $row1['id'];
// get all products from products table
$check = mysql_query("SELECT facebook_id as fid, id as uid,
TIMESTAMPDIFF(SECOND, `time`, '$mytime') AS timediff
FROM `posts`
WHERE `facebook_id` != $fbid
HAVING `timediff` <= '180'
ORDER BY `time` DESC") or die(mysql_error());
if (mysql_num_rows($check) > 0)
{
$response["products"] = array();
while ($row = mysql_fetch_array($check))
{
// temp user array
$product = array();
$product["facebookid"] = $row["fid"];
$product["timediff"] = $row["timediff"];
$product["theirpostid"] = $row["uid"];
$product["mypostid"] = $mypostid;
// push single product into final response array
array_push($response["products"], $product);
}
}
}
$response["success"] = 1;
echo json_encode($response);
I guess this is because you set
$response["products"] = array();
inside every cycle. Move it out of this inner while.
Trying to create a page where users can create a character with a base, one marking and eye colour. The three descriptions are all stored in seperate tables and are called randomly. I would like to limit the amount of times they are called so the user can't run through them all until finding a combo they like.
<?php
if(!isset($_SESSION['count']))
$_SESSION['count'] = 0;
if($_SESSION['count'] < 5) {
$_SESSION['count']++;
$query = $mysqli->query("SELECT `base` FROM `bases` WHERE `type` = 'Starter' ORDER BY rand()");
while($info = $query->fetch_assoc()) {
$_SESSION['refreshresultbase'] = $info['base'];
}
$querymark = $mysqli->query("SELECT `marking` FROM `markings` WHERE `type` = 'Starter' ORDER BY rand()");
while($infomark = $querymark->fetch_assoc()) {
$_SESSION['refreshresultmarking'] = $infomark['marking'];
}
$query3 = $mysqli->query("SELECT `colour` FROM `eyes` WHERE `type` = 'Starter' ORDER BY rand()");
while($infoeye = $query3->fetch_assoc()) {
$_SESSION['refreshresulteyes'] = $infoeye['colour'];
}
}
?>
Still really really new to mysqli so I apologise if this is a simple error.
I got a table that contains ID, Names, message, and time, I want to select from the table only one message query from each ID, Currently I select all the messages, this is my code
$query= mysql_query("SELECT * FROM `table` ORDER BY `time`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo '</br>';
echo $msg;
}
That Shows all messages ordered by time, Is there is a way to select only one message query from each ID?
Thanks,
Klaus
If you want only one message you can use LIMIT like this
SELECT * FROM table ORDER BY time LIMIT 1
Or if you want only one message from some id then you can use GROUP BY
SELECT * FROM table ORDER BY time GROUP BY id
Sure, pretty straightforward
This will fetch all messages given ID:
$id = 10 //Get your id in any way you need
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo $msg;
}
and this will fetch only the first message given ID
$id = 10
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id LIMIT 1")or die(mysql_error());
$row = mysql_fetch_array($query));
if($row){
$msg = $row['message'];
echo $msg;
}else{
echo 'no messages for id '.$id;
}
My page displays an image, and I want to display the previous and next image that is relevant to the current one. At the moment I run the same query 3x and modify the "where" statement with =, >, <.
It works but I feel there must be a better way to do this.
The image id's are not 1,2,3,4,5. and could be 1,2,10,20,21 etc. But if it is much more efficient I am willing to change this.
mysql_select_db("database", $conPro);
$currentid = mysql_real_escape_string($_GET['currentid']);
$query ="SELECT * FROM database WHERE id ='".$currentid."' LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$current_id = $row['id'];
$current_header = $row['title'];
$current_description =$row['desc'];
$current_image = "http://".$row['img'];
$current_url = "http://".$row['id']."/".$db_title."/";
$current_thumb = "http://".$row['cloud'];
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id <'".$currentid."' ORDER BY id DESC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$previous_id = $row['id'];
$previous_header = $row['title'];
$previous_description =$row['desc'];
$previous_image = "http://".$row['img'];
$previous_url = "http://".$row['id']."/".$db_title."/";
$previous_thumb = "http://".$row['cloud'];
}else{
$previous_none = "true"; //no rows found
}
mysql_select_db("database", $conPro);
$query ="SELECT * FROM database WHERE id >'".$currentid."' ORDER BY id ASC LIMIT 1 ";
$result = mysql_query($query,$conPro) or die(mysql_error());
$affected_rows = mysql_num_rows($result);
if ($affected_rows==1)
{
$row = mysql_fetch_array($result)or die ('error:' . mysql_error());
$next_id = $row['id'];
$next_header = $row['title'];
$next_description =$row['desc'];
$next_image = "http://".$row['img'];
$next_url = "http://".$row['id']."/".$db_title."/";
$next_thumb = "http://".$row['cloud'];
}else{
$next_none = "true"; //no rows found
}
mysql_close($conPro);
Thank you for your time
You don't have to do select_db each time. Once you 'select' a db, it stays selected until you select something else.
You can't really get away from doing two separate queries to get the next/previous images, but you can fake it by using a union query:
(SELECT 'next' AS position, ...
FROM yourtable
WHERE (id > $currentid)
ORDER BY id ASC
LIMIT 1)
UNION
(SELECT 'prev' AS position, ...
FROM yourtable
WHERE (id < $currentid)
ORDER BY id DESC
LIMIT 1)
This would return two rows, containing a pseudofield named 'position' which will allow you to easily identify which row is the 'next' record, and which is the 'previous' one. Note that the brackets are required so that the 'order by' clauses apply to the individual queries. Without, mysql will take the order by clause from the last query in the union sequence and apply it to the full union results.
You can get the "previous" one first WHERE id <'".$currentid."' ORDER BY id DESC, and then query for two "above" it: SELECT * FROM database WHERE id >= '".$currentid."' ORDER BY id ASC then it takes only two queries instead of three.