Error on my PDO Construct - Php - php

It's whining of line 6: Warning: PDO::__construct() expects parameter 2 to be string, array given
Along with a line 7 error:
Fatal error: Call to a member function prepare() on a non-object in
How do I fix this? I've tested the query and it works fine..
<?php
## Loop through results from mysql
try{
#connection string
$dbconn = new PDO('mysql:host=localhost;port=3306;dbname=thedb',array(PDO::ATTR_PERSISTENT => true));
$q = $dbconn->prepare("SELECT thecol FROM thetbl");
#call stored proc
$q->execute();
#get the rows into an array
$result = $q->fetchAll();
foreach($result as $r){
$xmlUrl = $r['FW_ArtSrcLink'];
$ConvertToXml = simplexml_load_file($xmlUrl);
# -> Setup XML
$newsStory = $ConvertToXml->channel->item;
}
# -----> Load News Stories
for($i = 0;$i<sizeof($newsStory); $i++){
# Source of Article Info-->
$SrcTitle=$newsStory[$i]->title;
$SrcLink=$newsStory[$i]->link;
# Actual News Article Info -->
$title=$newsStory[$i]->title;
$desc=$newsStory[$i]->description;
# Output Results ------------>
echo '<hr>';
echo '<strong>'.'Title:'.$title.'</strong>'.'(via: <a href=\''.$SrcLink.'\'>'.$SrcTitle.'</a>'.'<br />';
//echo 'Link:'.$link.'<br />';
echo 'Description'.$desc.'<br>';
echo '<hr>';
}
} // try
catch(Exception $e){
$errorStored = $e->getMessage() . ' on ' .'/errors/fanwire_loop.php'; #where errors are stored
$pageDateOfError = '/aggregate_looping.php'.date('l jS \of F Y h:i:s A'); #inc the file and date into the file too
file_put_contents($errorStored,$pageDateOfError, FILE_APPEND | LOCK_EX);
} // catch
#Load in File
/*************************************************
$xmlUrl ="http://sports.espn.go.com/espn/rss/mlb/news";
$ConvertToXml = simplexml_load_file($xmlUrl);
# -> Setup XML
$newsStory = $ConvertToXml->channel->item;
# -----> Load News Stories
for($i = 0;$i<sizeof($newsStory); $i++){
// Source of Article Info-->
$SrcTitle=$newsStory[$i]->title;
$SrcLink=$newsStory[$i]->link;
// Actual News Article Info -->
$title=$newsStory[$i]->title;
$desc=$newsStory[$i]->description;
echo '<hr>';
echo '<strong>'.'Title:'.$title.'</strong>'.'(via: <a href=\''.$SrcLink.'\'>'.$SrcTitle.'</a>'.'<br />';
//echo 'Link:'.$link.'<br />';
echo 'Description'.$desc.'<br>';
echo '<hr>';
}
***********************************************/
?>

You're initializing the PDO object incorrectly, the second parameter of the constructor should be the username, not an array of options.
$dbconn = new PDO('mysql:host=localhost;port=3306;dbname=thedb',array(PDO::ATTR_PERSISTENT => true));
should be,
$dbconn = new PDO('mysql:host=localhost;port=3306;dbname=thedb',
'yourusername',
'yourpassword',
array(PDO::ATTR_PERSISTENT => true));
See the PHP manual page for PDO::__construct() for more information.
The second error you're getting because the $dbconn object wasn't created properly due to the first error.

Can u try
$dbconn = new PDO('mysql:host=localhost;port=3306;dbname=thedb');
$q = $dbconn->prepare("SELECT thecol FROM thetbl", array(PDO::ATTR_PERSISTENT => true));

Related

Passing variable in php as a parameter to mongodb remove() function

I want to remove a document in mongodb-php. I am accepting an id from the user and using that I want to delete the document but it gives me an error
"Deprecated: MongoCollection::remove(): Passing scalar values for the
options parameter is deprecated and will be removed in the near future
in C:\wamp\www..process.php on line 12".
here is my code
<?php
$m = new mongo();
echo "Connection to database successfully";
$db = $m->mydb;
echo "Database mydb selected";
$collection = $db->mycollection;
echo "Collection selected succsessfully";
$collection->remove(array("Team_ID"=>$_POST['team_id']),false);
echo "Documents deleted successfully";
$cursor = $collection->find();
// iterate cursor to display team_id of documents
echo "Updated document";
foreach ($cursor as $document) {
echo $document["Team_ID"] . "\n";
}
?>
As the error states, it doesn't accept scalar values as a second parameter. Instead, use an array with options (http://php.net/manual/en/mongocollection.remove.php).
$collection->remove(array('Team_ID' => $_POST['team_id']), array('justOne' => false));
As "justOne" is false by default, you can omit the second parameter.
$collection->remove(array('Team_ID' => $_POST['team_id']));

Load mysql data to Highcharts line chart using JSON

I'm trying to import my data from a database to a line chart (Highcharts). My code doesn't work.
Here is my PHP code:
<?php
require('../php/config.php');
$con=mysqli_connect("localhost", "root", "ginnastica", "progetto");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET['src']))
{
$records=array();
$records = select($mysqli,"SELECT Sesso AS name, Occupati AS data FROM occupazione WHERE Sesso='totale' AND Periodo LIKE '%2008'");
$rows = array();
$rows['name'] = 'Totale';
while($r = mysql_fetch_assoc($records)) {
$rows['data'][]=$r['data'];
}
return json_encode($rows);
}
else
return json_encode(array('status' => 'error', 'details' => 'no src provided'));
}
?>
It seems that "mysql_fetch_assoc" doesn't work. The output of my array $rows id that:
{
"name": "Totale"
}
There isn't an element called "data".
What am I doing wrong?
At first:
It would be worth to see what is in your ../php/config.php file, because the content of that file may impact the behavior of other lines you provided.
The structure and data (at least few lines of data) of occupazione table is also worth to see, because data or structure could change the output as well.
You are missing a { after the else, - as #Moppo already mentioned.
Warning on mysql_fetch_assoc
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Read more in php.net
After that and some more fixes I would finally write your code in the way close to that:
<?php
$con = mysqli_connect("localhost", "root", "ginnastica", "progetto");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['src'])) {
$records = $con->query("SELECT Sesso AS name, Occupati AS data FROM occupazione WHERE Sesso='totale' AND Periodo LIKE '%2008'");
$rows = array();
$rows['name'] = 'Totale';
while ($r = $records->fetch_assoc()) {
$rows['data'][] = $r['data'];
}
return json_encode($rows, JSON_NUMERIC_CHECK);
} else {
return json_encode(array('status' => 'error', 'details' => 'no src provided'));
}
As I said, we know nothing about database you work with, so my guess would be that your select returns no lines as a result. And then you got no data (only {"name": "Totale"}), just because while has nothing to iterate throw.

Results not being returned for MongoDB query in PHP

I am not getting any results returned from the database when accessing the PHP file directly, however all the echo checks below are returning expected results.
This is entire PHP file.
<?php
$ext = new ReflectionExtension('mongo'); // see http://php.net/manual/en/reflectionextension.getversion.php
var_dump($ext->getVersion()); // returns string(5) "1.3.4"
echo extension_loaded("mongo") ? "loaded<br />" : "not loaded<br />"; // check if driver installed - returns "loaded"
$dbhost = '127.x.xx.x';
$dbname = 'mydb';
$m = new Mongo("mongodb://$dbhost"); // also tried 'MongoClient' rather than 'Mongo'
if ($m == true) {
echo "<br />connected to {$m}<br />"; // returns "connected to 127.x.xx.x:27017
}
$db = $m->$dbname;
$collection = $db->myCollection;
echo "<br />my collection is called {$collection}<br />"; // returns "my collection is called mydb.myCollection"
$query = $collection->find();
if ($query == true) {
echo "<br />the find method works"; // this is being returned
}
foreach($query as $result) { // nothing is happening here
var_dump($result);
}
?>
Command line query for:
db.myCollection.find();
is returning expected results (there is one document).
What version of PECL mongo lib are you using? if >= 1.3.0 (we are now on 1.4.3 stable), the Mongo class is deprecated and you are encouraged to use MongoClient instead.
Please refer to phpDoc.
Solution
Adjust above code to:
$dbhost = 'username:password#127.x.xx.x:27017/';
$dbname = 'yourdbname';
$m = new MongoClient("mongodb://$dbhost");
In my case I needed to define IP address.

DEBUG PDO Connection & PHP Output

I am trying to connect to mySQL using PDO.
Please forgive me if I have made a glaring error - I am just learining...
<?php
try {
$db_conn = new PDO('mysql:host=localhost;dbname=testdatabase','test', 'testpass');
}
catch (PDOException $e) {
echo 'Could not connect to database';
}
$stmt = $db_conn->query('SELECT * FROM PRODUCTS');
while ($row = $stmt->fetch() ) {
echo '<pre>'; print_r($row); echo '<pre>';
}
?>
the output from the browser is as follows:
query('SELECT * FROM PRODUCTS'); while ($row = $stmt->fetch() ) { echo '
'; print_r($row); echo '
';
}
?>
What have I done wrong??? why is PHP not parsing the PHP script?
UPDATE:
If I create a new php file, and run phpinfo(); it works.
If I paste phpinfo() into the top of the above code as follows:
<?php
phpinfo();
echo '<h1>PDO TEST</h1>';
try {
$db_conn = new PDO('mysql:host=localhost;dbname=testdatabase','test', 'testpass');
}
catch (PDOException $e) {
echo 'Could not connect to database';
}
$stmt = $db_conn->query('SELECT * FROM Products');
while ($row = $stmt->fetch() ) {
echo '<pre>'; print_r($row); echo '<pre>';
}
?>
I get the following output:
PDO TEST'; try { $db_conn = new PDO('mysql:host=localhost;dbname=testdatabase','test', 'testpass'); } catch (PDOException $e) { echo 'Could not connect to database'; } $stmt = $db_conn->query('SELECT * FROM Products'); while ($row = $stmt->fetch() ) { echo '
'; print_r($row); echo '
';
}
?>
UPDATE:
Problem solved... It was some kind of file encoding issue. It works perfectly when I copy and paste the code into a new file. Very strange.
Open httpd.conf file and Add this line inside :
AddType application/x-httpd-php .php .phtml
This makes your PHP script execute by PHP interpreter.
Then restart apache server using /etc/init.d/apache2 or httpd restart

PHP + MongoHQ : MongoCursorException

I'm trying to use mongodb with PHP.
For that, I have created a MongoHQ instance, but for some reasons when I try to insert something or any other operation from my php server I get the following error:
Fatal error: Uncaught exception 'MongoCursorException' with message 'unauthorized for db [datab] lock type: -1 ' in C:\Program Files\EasyPHP5.3.0\www\application\controllers\Stat.ctrl.php:56
Stack trace:
#0 C:\Program Files\EasyPHP5.3.0\www\application\controllers\Stat.ctrl.php(56): MongoCursor->rewind()
#1 C:\Program Files\EasyPHP5.3.0\www\index.php(105): Stat->index()
#2 {main} thrown in C:\Program Files\EasyPHP5.3.0\www\application\controllers\Stat.ctrl.php on line 56
Does anyone know where it can be coming from?
This is the php code I'm using:
$username = 'test';
$password = 'test';
try
{
$link = new Mongo( "flame.mongohq.com:27022/datab -u <".$username."> -p <".$password.">" );
//MongoDB::authenticate ( $username , $password )
//$link = new Mongo();
}
catch(MongoConnectionException $e)
{
die('Could not connect. Check to make sure MongoDB is running.');
}
$db = $link->datab;
$col = $db->order;
try
{
// Insert a document (row) into the collection (table)
$doc = array('login' => 'jsmith', 'password' => ' 5f4dcc3b5aa765', 'email' => 'jsmith#example.com');
$col->insert($doc, true);
$doc = array('login' => 'psmith', 'password' => ' 5f4dcc3b', 'email' => 'psmith#example.com');
$col->insert($doc, true);
}
catch(MongoCursorException $e)
{
echo 'Je suis la!';
}
// Get the id of last insert
$id = $doc['_id'];
// Get all documents
$res = $col->find();
echo 'All documents:<br/>';
foreach($res as $doc)
{
echo '<pre>';
print_r($doc);
echo '</pre>';
}
// Query for the document matching the last insert ID
$doc = $col->findone(array('_id' => $id));
echo 'Single document (_id = $id):<br/><pre>';
print_r($doc);
// Update a document
$col->update(array('_id' => $id), array('$set' => array('password' => 'b497dd1a701a33033620780d')));
// Query the updated docuemnt
$doc = $col->findone(array('_id' => $id));
echo 'Updated docuement:<br/><pre>';
print_r($doc);
echo '</pre>';
That is not the connection format MongoDB uses. See http://www.php.net/manual/en/mongo.construct.php.
You probably need to change it to something like:
$m = new Mongo("mongodb://$username:$password#flame.mongohq.com:27022/datab");

Categories