PHP Connecting to Twitter API and storing to mysql database - php

I'm brand new to the world of databases... I'm trying to connect to the twitter API from a search query and than post the results to a database in mysql (creating the database in the process if no database exists)... I apologize if my code is kind of scattered and fragmented, this is a group project for a class and my group isn't exactly the cleanest of coders... Any ideas/thoughts or pointing out anything that seems to be done incorrectly would be a huge help. Thanks...
After typing in a query, this is the error received:
The twitter
Database does not exist. Creating it now ....
Warning: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1045] Access denied for user 'root'#'localhost' (using password: YES)' in C:\xampp\htdocs\TwitterDB\database\database.php:17 Stack trace: #0 C:\xampp\htdocs\TwitterDB\database\database.php(17): PDO->__construct('mysql:host=loca...', 'root', 'sesame') #1 C:\xampp\htdocs\TwitterDB\searchDB.php(8): Database->__construct('twitter') #2 {main} thrown in C:\xampp\htdocs\TwitterDB\database\database.php on line 17
Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\TwitterDB\database\database.php on line 17
This is my database.php
class Database {
var $db;
public function __construct($dbname) {
$dsn = 'mysql:host=localhost;dbname=' .$dbname;
$username = 'root';
$password = 'sesame';
try {
$this ->db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo '<br> The <b>' .$dbname . '<br> Database does not exist. Creating it now .... <b>';
try {
$this ->db = new PDO('localhost', $username, $password);
$sql = "create database twitter;
use twitter;
create table tweets(
id VARCHAR(30) NOT NULL,
date dateTime,
from_user_id INT,
from_user_name VARCHAR(30),
to_user_id INT,
to_user_name VARCHAR(30),
geo VARCHAR(30),
profile_image_url VARCHAR(200),
text VARCHAR(150),
PRIMARY KEY (id, date, from_user_id)
)";
$this ->db ->exec($sql);
echo 'Done!<br>';
} catch (PDOException $e) {
echo $e ->getMessage();
exit();
}
}
}
public function close() {
try {
$this ->db - null;
} catch (PDOException $e) {
echo $e ->getMessage() . "Exit!";
exit();
}
}
public function insertTweets($tweets) {
$sql = "INSERT INTO TWEETS
(id, date, from_user_id, from_user_name, profile_image_url, text)
VALUES (:id, :date, :from_user_id, :from_user_name, :profile_image_url, :text)";
try {
$x = $this ->db ->prepare($sql);
foreach($tweets as $t) {
$parameters = array(
':id'=> $t ->id,
':date'=> date('Y-m-d- H:i:s', strtotime($t ->date)),
':from_user_id'=> $t ->from_user_id,
':from_user_name'=> $t ->from_user_name,
':profile_image_url'=> $t ->profile_image_url,
':text'=> $t ->text
);
$x ->execute($parameters);
}
} catch (PDOException $e) {
die ('Insert attempt failed:' . $e -> getMessage());
}
}
public function clearTable() {
try {
$x = $this ->db ->prepare('TRUNCATE TABLE tweets');
$x = execute();
} catch (PDOException $e) {
die('Attempt failed:' . $e ->getMessage());
}
}
public function search($query) {
try {
$x = $this ->db ->prepare($query);
$x -> execute();
} catch (PDOException $e) {
die ('Query failed:' . $e -> getMessage());
}
echo '<table border = 1>';
$heading = true;
while ( ($row = $x -> fetch(PDO::FETCH_ASSOC))) {
echo '<tr>';
if ($heading) {
$keys = array_keys($row);
foreach ($keys as $k) {
echo '<th>' .$k . '<th>';
}
echo '</tr><tr>';
$heading = false;
}
foreach($row as $r => $v) {
echo '<td>' . $v . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
This is my insertDB.php
<?php
ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "3219120843-cvff5Rj8LeFnmm6aM2eSdWN7bEKRwmjnJW64Wms",
'oauth_access_token_secret' => "MZS2Om2TRr9e56fgLAjWx7iwX3n7Svz18ya5iAXyWeMQS",
'consumer_key' => "y4sArn9Zl4DaA8KTPLIxFXVh8",
'consumer_secret' => "5Yj9soIQtLoQqbiXIgo1PhMSvI5sExsg13REHWGa1pPTzhTr2p"
);
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q='.$_POST['keyword'];
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$result = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$tweets = json_decode($result);
$tweet = $tweets->statuses;
echo $result;
require 'data_model.php';
$records = tweets2array($tweet);
require 'view.php';
echo tweet_obj_array2table($records);
$tweets = json_decode($result)->results;
$objects = tweets2array($tweets);
echo 'Total tweets:' . count($objects);
$database = new Database('twitter');
$table = 'tweets';
$database -> insertTweets($objects);
$database -> close();
?>
And this is my datamodel.php
<?php
function tweets2array($tweets) {
$records = array();
foreach($tweets as $tweet) {
$t = new stdClass();
$t->sender = $tweet->user->name;
$t->text = $tweet->text;
$t->time = $tweet->created_at;
$t->image = $tweet->user->profile_image_url;
$records[] = $t;
}
return $records;
}
?>

It appears that your database credentials do not have the right permissions to your database. I would recommend validating them again and the flushing the privileges. This should resolve the issue.

Related

Create my oracle oci class in php. But data show 1 first record only

This code from my PHP Project.
and create oracle connection class.
modified from mysql connection class(work fine).
class databaseOracle
{
public $oci;
public $connected = false;
public $parameters;
public $result;
function __construct($host, $dbPort, $dbName, $userDB, $passwordDB)
{
try {
$ociDB = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host . ")(PORT = " . $dbPort . ")))(CONNECT_DATA=(SID=" . $dbName . ")))";
$this->oci = oci_connect($userDB, $passwordDB, $ociDB, 'AL32UTF8');
if (!$this->oci) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
echo "Database oracle connection Failed.</br>";
exit();
} else {
echo "Database oracle connection success.</br>";
}
} catch (EngineExcpetion $e) {
echo "Error : " . $e->getMessage() . "</br>";
}
// exit();
}
public function bind($para, $value)
{
$this->parameters[count($this->parameters)] = ":" . $para . "\x7F" . $value;
}
public function bindParams($parray)
{
if (empty($this->parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
public function queryString($showQuery = 0, $query = "", $parameters = "")
{
$this->result = null;
if ($showQuery == 1) {
require_once('SQLFormatter.php');
echo SqlFormatter::format($query);
var_dump($parameters);
}
$this->result = oci_parse($this->oci, $query);
# Add parameters to the parameter array
$this->bindParams($parameters);
# Bind parameters
if (!empty($this->parameters)) {
foreach ($this->parameters as $param) {
$parameters = explode("\x7F", $param);
oci_bind_by_name($this->result, $parameters[0], $parameters[1]);
}
}
oci_execute($this->result);
$r = oci_fetch_array($this->result, OCI_ASSOC + OCI_RETURN_LOBS + OCI_RETURN_NULLS);
$this->parameters = array();
return $r;
}
}
$oracleDB = new databaseOracle($ociHost, $ociPort, $ociDB, $ociUsername, $ociPassword);
$query = $oracleDB->queryString(0,"SELECT * from SOME_TABLE where CREATED_BY = :created FETCH NEXT 50 ROWS ONLY",array("created" => "2"));
print_r($query);
my problem
i'm create class of oracle connection. modify from mysql connection class.
it's can query and read record from oracle database. example 50 record
but array result of query show first row only.

Uncaught Error: Call to a member function prepare() (PDO, php)

I'm trying to get data from a table using a public function in PHP, but I get this error:
Uncaught Error: Call to a member function prepare() (PDO, php)
I'm searching for 2, 3 hours... But no result is similar or I did not understand.
<?php
class Config {
public static $SQL;
private function __construct() {
$host_name = "localhost";
$base_user = "root";
$base_pass = "";
$base_name = "home_page";
try {
self::$SQL = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);
self::$SQL->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
die("Something went wrong, database connection closed. Reason: ". $e->getMessage());
}
}
public static function GetData($table, $data, $id) {
$wc = Config::$SQL->prepare('SELECT `'.$data.'` FROM `'.$table.'` WHERE `ID` = ?');
$wc->execute(array($id));
$r_data = $wc->fetch();
return $r_data[$data];
}
}
?>
And I use this in my base file:
<h1><?php echo Config::GetData("page_details", "Moto", 1) ?></h1>
The error is from this line:
$wc = self::$SQL->prepare('SELECT `'.$data.'` FROM `'.$table.'` WHERE `ID` = ?');
Is there any particular reason why you want to use STATICeverywhere? The common approach is using public, dynamic methods and properties. I rewrote your sample with suggested naming convention in PHPs OOP, it works:
<?php
class Config
{
/** #var PDO $conn */
private $conn = null;
public function __construct()
{
$host_name = "localhost";
$base_user = "root";
$base_pass = "";
$base_name = "home_page";
try {
$this->conn = new PDO("mysql:host=$host_name;dbname=$base_name", $base_user, $base_pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully"; // <- this is unnnesesary
} catch (PDOException $e) {
die("Something went wrong, database connection closed. Reason: " . $e->getMessage());
}
}
public function findById($table, $data, $id)
{
$stmt = $this->conn->prepare('SELECT `' . $data . '` FROM `' . $table . '` WHERE `uid` = ?');
$stmt->execute(array($id));
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
// just for test
$cfg = new Config();
print_r($cfg->findById('foo', '*', 1));
or in your case
<?php echo $cfg->findById("page_details", "Moto", 1)['Moto'] ?>

PHP MySQL PDO SQLSTATE[HY000]: General error

Please help fix "SQLSTATE[HY000]: General error:" in the following PHP script. Also, refer to the MySQL script in case.
<?php
# MySQL
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'procdb';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to MySQL Server successfully." . "\n";
$sql = "CALL prepend('abcdefg', #inOutParam);";
$stmt = $pdo->query($sql);
do {
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rows) {
foreach($rows as $row) {
print($row[0] . "\n");
}
}
} while ($stmt->nextRowset());
} catch (PDOException $e) {
#die("Could not connect to the database $dbname :" . $e->getMessage());
$error = $e->getMessage();
echo $error . "\n";
} catch (Exception $e) {
$error = $e->getMessage();
echo $error . "\n";
} finally {
$pdo = null;
echo "Connection closed." . "\n";
}
?>
Here's the MySQL Script:
DROP DATABASE IF EXISTS procdb;
DELIMITER $$
CREATE DATABASE procdb;$$
DELIMITER ;
USE procdb;
DROP PROCEDURE IF EXISTS prepend;
DELIMITER $$
CREATE PROCEDURE prepend
(
IN inParam VARCHAR(255),
INOUT inOutParam INT
)
BEGIN
DECLARE z INT;
SET z = inOutParam + 1;
SET inOutParam = z;
SELECT inParam;
SELECT CONCAT('zyxw', inParam);
END;$$
DELIMITER ;
USE procdb;
CALL prepend('abcdefg', #inOutParam);
/*
# Output
// (FieldName1 and its value)
inParam
'abcdefg'
// (FieldName2 and its value)
CONCAT('zyxw', inParam)
'zyxwabcdefg'
*/
What is the cause of the error? Note that adding "$stmt->close();" or "$stmt->closeCursor();" did not help.
Please help.
Thanks
Try this, line
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
Outside While loop
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to MySQL Server successfully." . "\n";
$sql = "CALL prepend('abcdefg', #inOutParam);";
$stmt = $pdo->query($sql);
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rows as $row) {
foreach ($row as $col) {
print $col . "\n";
}
}
$stmt->nextRowset();
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rows as $row) {
foreach ($row as $col) {
print $col . "\n";
}
}
} catch (PDOException $e) {
#die("Could not connect to the database $dbname :" . $e->getMessage());
$error = $e->getMessage();
echo $error . "\n";
} catch (Exception $e) {
$error = $e->getMessage();
echo $error . "\n";
} finally {
$pdo = null;
echo "Connection closed." . "\n";
}

Undefined index:session LOOP NOT WORKING php, pdo oop

I make users online page using PHP - OOP - PDO
include_once '../database.php';
$db = new database();
$getRows = $db->getRows('select * from visitors_online');
$gr = $db->rowCount();
$online = '';
$getRow = $db->getRow('select * from user_online');
$gr2 = $db->rowCount();
if(!empty($gr2)) {
try {
while ($getR = $getRow){
$getRow = $db->getRow('select * from users where id = ?',[$getR['session']]);
echo ', &nbsp '.$getRow['username'].' &nbsp ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
The problems is:
* Not show any users except Admin, also I got this :
ONLINE
admin
Notice: Undefined index: session in /Applications/MAMP/htdocs/baws/admin/online.php on line 56
,
.Users = 0 ,Member = 2 , Register = 2
Who is online list
Here is the function from Database class
// Get row by id, username, or email etc..
public function getRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return $this->stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
Any Help
Thanks
I tried to simplify a bit your code as I do not know your class details and it s messy.
The problem is you are not binding stuff properly neither fetching them properly too. Also, you are preparing the second query, each time you loop inside the query 1 results , that is useless. prepare both (withyour class or not) and just bind and execute.
$stmt1 = $db->prepare('select * from user_online where id= ?');
$result1 = getRows($stmt1, "1");
$gr1 = $db->rowCount();
if (!empty($gr1)) {
$stmt2 = $db->prepare('select * from users where id = ?');
foreach ($result1 as $key1 => $h1) {
$stmt2->bindParam(1, $h1['session'], PDO::PARAM_INT);
$stmt2->execute();
$result2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
if (count($result2) !== 0) {
foreach ($result2 as $key2 => $r2) {
echo ', &nbsp ' . $r2['username'] . ' &nbsp ';
}
}
}
}
function getRow($query, $para) {
$stmt1->bindParam(1, $para, PDO::PARAM_INT);
try {
$stmt1->execute($para);
$result1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
return $result1;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
Please find the database class here
class database {
public $isConn;
protected $datab;
private $stmt;
public function __construct() {
$this->connect();
}
// connect to database
private function connect(){
$host = 'localhost';
$db = 'baws';
$user = 'root';
$pass = 'root';
$option = [];
$this->isConn = TRUE;
try {
$this->datab = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pass, $option);
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo '<h3>Not connected</h3>' . $e->getMessage();
}
}
// Disconnected from database
private function disconnect(){
$this->isConn = NULL;
$this->datab = FALSE;
}
//insert to database
public function insertRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return TRUE;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
//update row to database
public function updateRow($query, $para = []){
$this->insertRow($query, $para);
}
//Delete row from database
public function deleteRow($query, $para = []){
$this->insertRow($query, $para);
}
// Get row by id, username, or email etc..
public function getRow($query, $para = []){
try {
$this->stmt = $this->datab->prepare($query);
$this->stmt->execute($para);
return $this->stmt->fetch();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
}
online.php Page
ob_start();
echo "ONLINE <br>";
include_once '../database.php';
$db = new database();
try {
$session=$_COOKIE['id'];
$time=time();
$time_check=$time-300; //SET TIME 10 Minute
$getRow = $db->getRow("SELECT * FROM user_online WHERE session = ?", [$session]);
$count =$db->rowCount($getRow);
if($count == '0'){
$insertRow = $db->insertRow("INSERT INTO user_online(session, time)VALUES(? , ?)",[$session, $time ]);
}
elseif($count != '0'){
$updateRow = $db->updateRow("UPDATE user_online SET time = ? WHERE session = ?", [$time, $session]);
}else{
$deleteRow = $db->deleteRow("DELETE FROM user_online WHERE time < ? ", [$time_check]);
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
try {
$ip=$_SERVER['REMOTE_ADDR'];
$session=$ip;
$time=time();
$time_check=$time-300; //SET TIME 10 Minute
$deleteRow = $db->deleteRow("DELETE FROM visitors_online WHERE time < ? ", [$time_check]);
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
$getRows = $db->getRows('select * from visitors_online');
$gr = $db->rowCount();
$online = '';
$getRow = $db->getRow('select * from user_online');
$gr2 = $db->rowCount();
if(!empty($gr2)) {
try {
while ($getR = $getRow){
$getRow = $db->getRow('select * from users where id = ?',[$getR['session']]);
echo ', &nbsp '.$getRow['username'].' &nbsp ';
}
} catch (PDOException $e) {
die('Error :'. $e->getMessage());
}
$total = $gr + $gr2;
} //end

Unable to get error info with PDO in PHP

I am in the process of learning PDO and am trying to implement it in my current project. When I used mysqli, I could get detailed info about any error using mysqli_error($connection). I googled at what the comparable for PDO would be and found this post, and decided to implement it in my code. However, I am unable to get any error messages even when I know there is an obvious error in the sql statement.
Relevant code:
class Database {
public $connection;
function __construct() {
$this->open_database_connection();
}
public function open_database_connection() {
try {
$this->connection = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
echo $e->getMessage();
die('Could not connect');
}
} // end of open_database_connection method
public function query($sql, $params = []) {
try {
$query = $this->connection->prepare($sql);
} catch (Exception $e) {
var_dump('mysql error: ' . $e->getMessage());
}
foreach($params as $key => $value) {
if ($key === ':limit') {
$query->bindValue($key, $value, PDO::PARAM_INT);
} else {
$query -> bindValue($key, $value);
}
}
try {
$query->execute();
} catch(Exception $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}
/*
DID NOT WORK:
if (!$query->execute()) {
print_r($query->errorinfo());
}*/
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$this->confirm_query($result);
return $result;
} // end of query method
function confirm_query($query) {
if (!$query) {
die('mysql error: ');
}
}
When I run the code, I do get the "mysql error", but I do not get any details about it. What am I doing wrong?
Update: As requested, I am providing additional details below.
What I am trying to do is get the user's login detail to be verified. To that end, once the user inputs his credentials , this code runs:
if (isset($_POST['submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//check the database for the user
$user_found = User::verify_user($username, $password);
Relevant code from the User class:
public static function verify_user($username, $password) {
global $db;
$username = $db->escape_string($username);
$password = $db->escape_string($password);
$values = [ ":username" => $username,
":password" => $password,
":limit" => 1
];
$result_array = self::find_this_query("SELECT * FROM users WHERE username=:username AND password=:password LIMIT :limit", true, $values);
return !empty($result_array)? array_shift($result_array) : false;
}
public static function find_this_query($sql, $prepared = false, $params = []) {
global $db;
$the_object_array = array();
$result = $db->query($sql, $params);
$arr_length = count($result);
for ($i = 0; $i < $arr_length; $i++) {
$the_object_array[] = self::instantiation($result[$i]);
}
return $the_object_array;
}
public static function instantiation($the_record) {
$the_object =new self; //we need new self because $the_record corresponds to one user!
foreach($the_record as $the_attribute => $value) {
if ($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
public function has_the_attribute($attribute) {
$object_properties = get_object_vars($this);
return array_key_exists($attribute, $object_properties);
}
You have to use PDO::errorInfo():
(...)
public function query($sql, $params = []) {
try {
$query = $this->connection->prepare($sql);
if( !$query )
{
$error = $this->connection->errorInfo();
die( "mysql error: {$error[2]}" );
}
} catch (Exception $e) {
var_dump('mysql error: ' . $e->getMessage());
}
(...)
}
PDO::errorInfo returns an array:
Element 0: SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard);
Element 1: Driver-specific error code;
Element 2: Driver-specific error message.

Categories