Inserting user tweets into mysql table - php

I am getting user tweets and mentions and inserting into table. Once this process completes, I redirect to next page.
For few users it correctly stores and display tweets and redirect to next page. But for few user, it stuck on the first page where I get tweets and store into table. I am trying since last few days to overcome this.
Can any one tell me what problem can cause this? Does it is due to it unable to store the data (tweet text) into table?
There are two function in which I perform insert operation:
function lookup($tweetid,$connection,$userid)
{
$tweets5 = $connection->get("https://api.twitter.com/1.1/statuses/retweets/".$tweetid.".json?count=1");
//var_dump($tweets5);
$json = json_encode($tweets5);
foreach($tweets5 as $item)
{
$text = $item->text;
$text_id = $item->id;
// $user_id = $item->user->id;
$name = $item->user->name;
$constant = 'retweet';
$time = $item->created_at;
$dt = \DateTime::createFromFormat('D M d H:i:s e Y', $time);
// $dt = new \DateTime($time);
$tweet_time = $dt->format('H:m:s');
$tweet_dtm = $dt->format('Y:m:d');
$year = $dt->format('Y');
$month = $dt->format('m');
echo $text."-".$text_id."-".$name."-".$time."-".$tweet_time.$tweet_dtm.$year.$month.$rt_count.$follower.$friend."<br>";
echo "<br>";
$inreplyto = $item->in_reply_to_screen_name;
$follower = $item->user->followers_count;
$rt_count = $item->retweet_count;
$friend = $item->user->friends_count;
$con = mysqli_connect('127.0.0.1', 'root', 'karim', 'karim');
$text = mysql_real_escape_string($text);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$insertQuery1 = "INSERT INTO twitter_retweet(`username`,`userid`,`tweet_text`,`text_id`,`time`,`month`,`year`,`date`,`user_follower_count`,`rt_count`,`constant`,`in_reply_to`) VALUES ('".$name."','".$userid."','".$text."','".$text_id."','".$tweet_time."','".$month."','".$year."','".$tweet_dtm."','".$follower."','".$rt_count."','".$constant."','".$inreplyto."')";
if (!mysqli_query($con,$insertQuery1))
{
die('Error: ' . mysqli_error($con));
// echo "error";
}
// echo "Text : $text <br> ID : $user_id <br> Name : $name <br> Follower : $follower <br> Friends : $friend <br> ---";
}
}
Is there anything wrong in this code? I am not sure whether it stuck here during insertion or what.
2nd function, this prints the data, but it does not store $text into database. why?:
foreach ($tweets1 as $item)
{
$text = $item->text;
//echo $userid.$text;
$text_id = $item->id;
$constant = 'mention';
$time = $item->created_at;
//echo $time;
//$dt = new DateTime('#' . strtotime($time));
$dt = \DateTime::createFromFormat('D M d H:i:s e Y', $time);
//var_dump($dt);
$tweet_time = $dt->format('H:m:s');
$tweet_dtm = $dt->format('Y:m:d');
$year = $dt->format('Y');
$month = $dt->format('m');
$user_name = $item->user->name;
// echo $year.$month.$user_name;
$inreplyto = $item->in_reply_to_screen_name;
$rt_count = $item->retweet_count;
$follower_count = $item->user->followers_count;
echo $text."-".$text_id."-".$time."-".$tweet_time.$tweet_dtm.$year.$month.$user_name.$rt_count.$follower_count."<br>";
echo "<br>";
$con = mysqli_connect('127.0.0.1', 'root', 'karim', 'karim');
//$text = mysqli_real_escape_string($text);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$insertQuery1 = "INSERT INTO twitter_mention(`username`,`userid`,`tweet_text`,`text_id`,`time`,`month`,`year`,`date`,`user_follower_count`,`rt_count`,`constant`,`in_reply_to`) VALUES ('".$twitteruser."','".$userid."','".$text."','".$text_id."','".$tweet_time."','".$month."','".$year."','".$tweet_dtm."','".$follower_count."','".$rt_count."','".$constant."','".$inreplyto."')";
if (!mysqli_query($con,$insertQuery1))
{
die('Error: ' . mysqli_error($con));
// echo "error";
}
}
This is the code at the end to redirect to next page:
echo '<form name="myForm" id="myForm" action="start.php" method="POST">
<input style="display:none" name="userid" value="'.$userid.'" />
</form>
<script>
function submitform()
{
document.getElementById("myForm").submit();
}
window.onload = submitform;
</script>
';

Related

How to get specific column form mysql (PDO)?

I have this code and in "SELECT * FROM Blogi WHERE PostID=".
How to get each line separately so that takes postedBY, title, date, content by PostID
<?php
try{
$Blog = $conn->prepare("SELECT * FROM Blogi WHERE PostID=");
$Blog->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
$fetch = $Blog->fetchAll();
$usercount = $Blog->rowCount();
if($usercount > 0){
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY'];
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
}
}else{
session_destroy();
header('location: index.php');
}
?>
I have very bad English, so I don't know anyone can understand this.
How to do it further this postID="" to that he would start to work?
You have already done it in foreach loop... so add a line for output like... Also you aren't sending any PostID value to your query, be sure that you are sending a value for it.
foreach($fetch as $f){
$PostID = $f['PostID'];
$PostedBY = $f['PostedBY']
$Title = $f['Title'];
$Date = $f['Date'];
$Content = $f['Content'];
echo $PostID . " " . $Title . " " . $Date . " " . $Content . "<br />";
}

Insert database with while loop

I want to create a function that select the begin date and end date and then insert into the database. I want to insert the date for every 4 days from 30/8 til 30/9 to the database...
For example:
table
row 1 = 30/8
row 2 = 3/9
row 3 = 7/9
row 4 = 11/9 ... and so on
My php:
<?php
$con = mysql_connect("localhost", "root", "root");
mysql_select_db("test", $con);
$start_date= "2015-08-30";
$end_date= "2015-09-30";
$insert = "INSERT INTO calendar(date)......";
if(mysql_query($insert,$con)) {
echo "<script> alert('Insert Successful'); </script>";
}
else {
echo "<script> alert('Insert Unsuccessful'); </script>";
}
while (strtotime($start_date) <= strtotime($end_date)) {
//echo "$start_date <br>";
$start_date = date ("Y-m-d", strtotime("+4 day", strtotime($start_date)));
}
Think this is what your searching for... let me know anything needed to change...
<?php
$start_date= "2015-08-30";
$end_date= "2015-09-30";
$inc_val = 4;
$start_con_to_time = strtotime($start_date);
$end_con_to_time = strtotime($end_date);
$days_between = ceil(abs($end_con_to_time - $start_con_to_time) / 86400);
for($x=$inc_val+1; $x<=$days_between;)
{
echo date('Y-m-d', strtotime($start_date. ' + ' . $x . 'days'));
echo ' : Add database code here <br>';
$x+=$inc_val;
}
?>

SQL Syntax Error via php

I'm kinda new to php, this place has been a great help for me so far! Anyway, I have this code
$month = "
SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '$vatsimid'
AND MONTH(atc_online) = " . $pmonth . "
AND YEAR(atc_online) = " . $year . "
";
That's what I get when I echo out $month
SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '1070757'
AND MONTH(atc_online) = 07
AND YEAR(atc_online) = 13
When i use this directly into phpMyAdmin, works as a charm, but when I try to do it through a php webpage, I get the syntax error. I'm using php 5.4
Thanks!
Edit: Full Code:
<?php
//open MySQL connection
$mysql = mysqli_connect('host', 'un', 'pass', 'table')
or die ( "MySQL Error: ".mysqli_error() );
//Get and decode residents data
$jsonData = file_get_contents("link");
$phpArray = json_decode($jsonData, true);
//Start Operations
foreach ($phpArray as $key => $value) {
//Get controller hours for today
$vatsimid = $value[vatsimid];
//Get previous month
$pmonth = date("m", strtotime("-35 days") ) ;
$pmonthName = date("M", strtotime("-35 days") ) ;
echo $pmonth;
echo $pmonthName;
//This year or last year?
If (date("M") != "Jan") { //Checks that it's not January of the next year.
$year = date("y");
}
else {
$year = date("y", strtotime("-1 month") );
}
echo $year;
//Search and sum entries during last month
$month = "SELECT SUM(`duration`)
FROM `connlist` AS `month_sum`
WHERE `vatsimid` = '$vatsimid'
AND MONTH(atc_online) = " . $pmonth . "
AND YEAR(atc_online) = " . $year . "";
echo $month;
echo "</br> </br>";
$result = mysqli_query($mysql,$month);
$row = mysqli_fetch_assoc($result);
$month_sum = $row['month_sum'];
echo $month_sum;
//Updates data in atclist
$datainsert = "
UPDATE `atclist`
SET " . $monthName . "=" . $month_sum . "
WHERE vatsimid = " . $vatsimid . "";
$insert = mysqli_query($mysql,$datainsert);
if (!$insert)
{
die('Error: ' . mysqli_error($mysql));
}
}
/*
Did you mean:
SELECT SUM(duration) AS month_sum
FROM connlist
WHERE vatsimid = '1070757' AND MONTH(atc_online) = 07 AND YEAR(atc_online) = 13
It looks like $month_sum variable is not set or empty in your UPDATE query.
You can add single quotes like
$datainsert = "
UPDATE atclist
SET ".$monthName."= '".$month_sum."'
WHERE vatsimid= '".$vatsimid."'";

How do I send a time to a MySql database with PHP?

I am trying to send a time to my MySql database on localhost using a simple PHP query. Here's the code.
On the HTML side:
<form action = "Timecard.php"
method = "get">
<fieldset>
<label>Enter employee number:</label>
<input type = "text"
name = "EmployeeNumber" />
<button type = "submit" name = "submit" value = "ClockIn">
Clock In
</button>
<button type = "submit" name = "submit" value = "ClockOut">
Clock Out
</button>
</fieldset>
</form>
And the PHP:
<?php
require ("conn.php");
$filled = true;
$EmpNum = $_REQUEST["EmployeeNumber"];
if ($EmpNum == "") {
$filled = false;
}
if ($filled == false) {
print "Must enter a valid employee number to log in. Click <a href = 'http://localhost/Employee Timecard/Timecard.html'>HERE</a> to return to the login screen";
} else {
$timestamp = $_SERVER['REQUEST_TIME'];
$date = date('Y-m-d', $timestamp);
$time = sprintf(date('h-i-s', $timestamp));
print $timestamp . "<br>";
print $EmpNum . " has just logged ";
if (($SubmitButton = $_REQUEST["submit"]) == "ClockIn") {
print "in on " . $date . " at " . $time;
$query = sprintf("INSERT INTO timestamp(EmployeeNumber, Date, TimeIn, TimeOut) VALUES (".$EmpNum.",'".$date."','".$time."','')");
print $query;
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
print "checkpoint 2";
} else if (($SubmittButton = $_REQUEST["submit"]) == "ClockOut") {
print "out on " . $date . " at " . $time;
$query = sprintf("INSERT INTO timestamp(EmployeeNumber, Date, TimeIn, TimeOut) VALUES (".$EmpNum.",'".$date."','',".$time.")");
print $query;
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
print "checkpoint 2";
}
}
print "<br>checkpoint 3";
?>
When I submit to the database the date goes through fine but the time is incorrect -- something like -00:00:47 or 00:00:05. The type of the field in the database is set to "time". Why would I be getting these results? It has to be simple, but it's driving me nuts.
You can simply use date() here,
$query = "INSERT INTO timestamp(EmployeeNumber, Date, TimeIn, TimeOut)
VALUES (".$EmpNum.",'".$date."','','".date('H:i:s')."')";
print $query;

php database problem

I have written this PHP code and worked correctly... then I wanted a particular code segment to be worked as a function, but as soon I did this I didn't get the correct result... I'm confused what has gone wrong, can somebody please help me with this... Thanks a lot...
Here's the code gives me the error...
$arr1=array();
$date = date("D");
$link = mysql_connect ('localhost', 'root', '');
$db = mysql_select_db ('dayevent', $link);
function grabData($arr){ //works properly NOT as a function, but I want to make this code part act like a funciton
$i=0;
$sql = "SELECT event FROM events WHERE day = '$date'";
$sel = mysql_query($sql);
echo $sel; //this prints Resource id #3
if (mysql_num_rows($sel) > 0) { // but doesn't go into if block
while($row = mysql_fetch_array($sel)) {
echo $row['event'] . '<br />';
//storing DB query result in array
$arr[$i]=$row['event'];
$i=$i+1;
}
foreach($arr as $key => $value) {
echo $key . " " . $value . "<br />";
}
} else echo 'Nothing returned!'; //prints this instead of the correct result
}
grabData($arr1);
mysql_close();
Move this inside your function: $date = date("D");. The way it is now, $date is not defined. If you run with error_reporting(E_ALL) you would have caught it right away.
Test Below Code :
EDITED
$arr1=array();
$date = date("D");
$link = mysql_connect ('localhost', 'root', '');
$db = mysql_select_db ('dayevent', $link);
function grabData()
{
global $link,$date;
$arr = array();
$i=0;
$sql = "SELECT event FROM events WHERE day = '$date'";
$sel = mysql_query($sql,$link);
echo $sel; //this prints Resource id #3
if (mysql_num_rows($sel) > 0)
{
while($row = mysql_fetch_array($sel))
{
echo $row['event'] . '<br />';
$arr[$i]=$row['event'];
$i=$i+1;
}
foreach($arr as $key => $value)
{
echo $key . " " . $value . "<br>";
}
} else echo 'Nothing returned!'; //prints this instead of the correct result
return $arr;
}
print_r( grabData() );
mysql_close();

Categories