I have in the database a list of links from which I want to take some data.
All the script is working, except the part when I'm taking the link from the DB and paste it in Simple DOM function.
"
include ('utile/db.php');
include_once('utile/simple_html_dom.php');
$dbh = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;", $username, $password);
$sth = $dbh->query("SELECT link FROM pilots where year = '2007' and Contry ='CZ' and zboruri <> '101' limit 3 ");
foreach ($sth as $url) {
functie ($url['link']);
}
function functie($lin){
$linkul=file_get_html("$lin");
// pages number
$paging = $linkul->find('div[class*=paging]',0);
echo $paging;
$numar=-4;
foreach($paging->find('a') as $element=>$item){$numar++;}
echo $numar;
}
"
I receive the following error:
Fatal error: Call to a member function find() on null in C:\xampp\htdocs\para\teste.php on line 269
If I change the link manually it will work.
I think it is something related how I extract the link from DB and insert it the function.
Thank you
The issue with fetchALL in foreach.
The line changed:
foreach($sth->fetchAll() as $url){
The final code that is working:
include ('utile/db.php');
include_once('utile/simple_html_dom.php');
$dbh = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;", $username, $password);
$sth = $dbh->query("SELECT link FROM pilots where zboruri > '101' limit 3");
foreach($sth->fetchAll() as $url){
functie ($url['link']);
}
function functie($lin){
var_dump($lin);
$linkul=file_get_html("$lin");
$paging = $linkul->find('div[class*=paging]',0);// pages number
echo $paging;
$numar=-4;
foreach($paging->find('a') as $element=>$item){$numar++;}
echo $numar;
}
Thank you for advices.
When I use PDO I use prepared statements, so the syntax on getting the result of the query is a little different... but I think that you need to fetch a row from your $sth since it would be a record set. Here's a snippit of what I do
$dbconn = new PDO('mysql:host='.$hostname.';port='.$dbPort.';dbname='.$dbName.';charset=utf8', $dbuser, $dbpass,array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result=$dbconn->prepare($query);
$result->execute($arr);
if(!$result){
// do your error handling, result is either false
// for error or contains a recordset
$errorMessage=$dbconn->errorInfo();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
while($row=$result->fetch()){
// do stuff here, $row is an associative array w/ the
//keys being the column titles in your db table
print_r($row);
}
Related
Just started learning PHP, Angular and mySQL and am trying to retrieve just one field value from one single row. The same code below works for a query that returns multiples rows:
$qry = "SELECT ID FROM SharePoint001 ORDER BY DownloadedTimeStamp DESC LIMIT 1"; //returns a5f415a7-3d4f-11e5-b52f-b82a72d52c35
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array("ID" => $rows['ID']);
}
print_r(json_encode($data[0]));
I highly recommend switching to the mysqli extension. It's a much better way of doing things and you will probably find it much easier.
Here's a simple mysqli solution for you:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
If you're grabbing more than one row, I do it like this:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With Error Handling: If there is a fatal error the script will terminate with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With try/catch exception handling: This lets you deal with any errors all in one place and possibly continue execution when something fails, if that's desired.
try {
if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
} catch (Exception $e) {
echo "DB Exception: ",$e->getMessage(),"\n";
}
The MySQL extension is:
Officially deprecated (as of PHP 5.5. Will be removed in PHP 7.)
Lacks an object-oriented interface
Much slower than mysqli
Not under active development
Does not support:
Non-blocking, asynchronous queries
Transactions
Stored procedures
Multiple Statements
Prepared statements or parameterized queries
The "new" password authentication method (on by default in MySQL 5.6; required in 5.7+)
Since it is deprecated, using it makes your code less future proof. See the comparison of SQL extensions.
You have not executed the query, so you'll never get results.
First you have to prepare query and place it into a variable lets say $qry.
Then execute that query by using mysql_query() function and capture result into a variable lets say $result
Now you can iterate that $result with loop to fetch rows and cells (what you call fields).
Below is code I have corrected:
$qry = "SELECT ID FROM SharePoint001 ORDER BY DownloadedTimeStamp DESC LIMIT 1";
$result = mysql_query($qry); // You are missing this line
$data = array();
while($rows = mysql_fetch_array($result)) // You have to pass result into mysql_fetch_array not query string
{
$data[] = array("ID" => $rows['ID']);
}
print_r(json_encode($data[0]));
I got an array taken from an mysqli query, this array contain a list of tasks. I must to count how many tasks is in the array ( so only the number of row ) and put in a icon badge as a human readable number.
try {
$db = new PDO("mysql:host=127.0.0.1;dbname=c9", "andreaem_dev", "");
//echo "Connected to database<br/>"; // check for connection
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$sql = "SELECT ID FROM data_tasks WHERE data_tasks . user = 'admin'"; //I'm selecting ID so only one element on the row is count
$result = $db->query($sql);
foreach ($result as $row) {
$row = $result->fetch(PDO::FETCH_NUM);
echo $row[0];
}
$db = null; // close the database connection
}
catch(PDOException $e) {
echo $e->getMessage();
}
With this code i get a int(2) response, the array contains 5 element and i don't know where it takes '2', even i must to convert it in a number.
Thanks in advice for help!
*sigh*
You need to use count() function in mysql. this is how databases intended to work: they count your data for you. You don't need to count by hand. You don't need to select id. You don't need to loop over results. You don't need to convert number to string. You just have to ask database to count and then get the result.
$db = new PDO("mysql:host=127.0.0.1;dbname=c9", "andreaem_dev", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT count(*) FROM data_tasks WHERE user = 'admin'";
$count = $db->query($sql)->fetchColumn();
This question already has answers here:
How to fetch a row with PDO
(2 answers)
Closed 8 years ago.
I am building a login script using the PDO method. I would like to register some sessions from the user account. Every time I try to pull information from the database I get blank. I am new to PDO. Here is what I have so far:
try{
$conn = new PDO(...........);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$conn->exec("SET CHARACTER SET utf8");
$sql = "SELECT * FROM $table WHERE USER = ':user' AND pass = ':pass'";
$UpdateSql = $conn->prepare($sql);
$UpdateSql->bindValue(':user',$user,PDO::PARAM_STR);
$UpdateSql->bindValue(':pass',$pass,PDO::PARAM_STR);
$results = $UpdateSql->execute();
/*Here is where the error comes in
foreach($results as $row)
{
$_SESSION['account'] = $row['account'];
}
*/
/*I also tried this
foreach($UpdateSql as $row)
{
$_SESSION['account'] = $row['account'];
}
*/
}catch(PDOException $e){
echo $e->getMessage();
}
When I tried the first foreach() I received an error Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\drug_center\dc_login.php on line 26 and the second foreach() gave me an empty result. Can someone please explain to me where I am making my mistake?
You'll be needing the $UpdateSql->fetchAll() method. This will give you a result set which can be traversed.
Secondly you'll be specyfing the parameters trough bindValue, so you don't need the ' around the values.
$table = (in_array($table, array('table1','table2')) ? $table : false;
//make sure you put some input-validation on the $table variabel!!
if($table){
$sql = "SELECT * FROM $table WHERE user = :user AND pass = :pass";
//lose the ' around the :pass
$UpdateSql = $conn->prepare($sql);
$UpdateSql->bindValue(':user',$user,PDO::PARAM_STR);
$UpdateSql->bindValue(':pass',$pass,PDO::PARAM_STR);
$UpdateSql->execute();
foreach($UpdateSql->fetchAll() AS $row){
// do some magic
}
}else{
throw new Exception("Error: table not allowed", 1);
}
Execute is to run a stored procedure on a SQL Server, you can
$results = $UpdateSql->fetchAll($sql);
foreach ($results as $row)
//stuff
}
The function prepare() returns an object of PDOStatement class. As it says on the PHP manual, PDOStatement::execute() does not return results, it returns a boolean instead to indicate if the query was successful or not. You need to use the fetch commands the PDOStatement has.
I am using the mysqli functions (mysqli_connect, mysqli_select_db, mysqli_query) to call 1 select query and 2 stored procedures.
It seems that when I am using the same $connection (returned by mysqli_connect) multiple times, I am getting the following error message: "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in..."
Below is my code:
<?php
$server="localhost";
$user="user";
$pass="pass";
$db="db";
$connection=mysqli_connect("$server","$user","$pass");
mysqli_select_db($connection, "$db") or die('Unable to select database.');
//First SELECT using $connection
$query=mysqli_query($connection, "SELECT item_name FROM items ORDER BY item_name DESC");
While ($result=mysqli_fetch_array($query,MYSQL_NUM))
{
$complete_result[] = $result[0];
$total_rows = $total_rows + 1;
}
//CALL to first sp using $connection
$query2 = mysqli_query($connection, "CALL sp_check_edits_remaining()");
while ($row2 = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$edits_remaining = $row2['edits_remaining'];
} // End while
//CALL to second sp using $connection
$query3 = mysqli_query($connection, "CALL sp_edit_data");
while ($row3 = mysqli_fetch_array($query3, MYSQL_ASSOC)) {);
$edits_id = $row3['id'];
} // End while
?>
Like I described, when I call the second sp, the above code gives me the error message mentioned above. (Please note that the connection is never closed.)
However, when I create another connection and provide it to the second sp call, this error disappears. This is shown in the code below
$connection2=mysqli_connect("$server","$user","$pass");
mysqli_select_db($connection2, "$db") or die('Unable to select database.');
//CALL to second sp using $connection
$query3 = mysqli_query($connection2, "CALL sp_edit_data");
while ($row3 = mysqli_fetch_array($query3, MYSQL_ASSOC)) {
$edits_id = $row3['id'];
} // End while
Can anyone please help me why this unexpected behavior?
Thanks and in advance!
It seems I have found a solution, which might be specific to my scenario.
My stored procs return only one row in the resultset.
So, after the CALL to the first sp and the corresponding while loop, I have simply added:
mysqli_next_result($connection);
This has removed the error message/warning I was receiving.
Anyone wants to comment whether this is the 'professional' approach?
You have an error somewhere, causing one of the mysql functions (probably the query call(s)) to return a boolean false, which you then blindly use in a fetch call. You need to add extra error handling, e.g.
$query = mysqli_query($connection, "...") or die(mysqli_error($connection));
never assume a query has succeeded.
enter code hereafter the query is finished, you must close the $connection then for another query, connect and assign the $connection again.
mysqli_close($connection);
$connection=mysqli_connect(bla,bla,bla,bla).
Sample code:
$infoArray = array();
require_once("connectAndSelect.php");
// Connects to mysql and selects the appropriate database
$sql = "SOME SQL";
if($results = mysql_query($sql))
{
while($result = mysql_fetch_array($results, MYSQL_ASSOC))
{
$infoArray[] = $result;
}
}
else
{
// Handle error
}
echo("<pre>");
print_r($infoArray);
echo("</pre>");
In this sample code, I simply want to get the result of my query in $infoArray. Simple task, simple measures... not.
I would have enjoyed something like this:
$sql = "SOME SQL";
$infoArray = mysql_results($sql);
But no, as you can see, I have two extra variables and a while loop which I don't care for too much. They don't actually DO anything: I'll never use them again. Furthermore, I never know how to call them. Here I use $results and $result, which kind of represents what they are, but can also be quite confusing since they look so much alike. So here are my questions:
Is there any simpler method that I
don't know about for this kind of
task?
And if not, what names do you
give those one-use variables? Is
there any standard?
The while loop is really only necessary if you are expecting multiple rows to be returned. If you are just getting one row you can simply use mysql_fetch_array().
$query = "SOME SQL";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
For single line returns is the standard I use. Sure it is a little clunky to do this in PHP, but at least you have the process broken down into debug-able steps.
Use PDO:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
$sql = "SELECT * FROM myTable";
$result = $dbh->query($sql)
//Do what you want with an actual dataset
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Unless you are legacied into it by an existing codebase. DONT use the mysql extension. Use PDO or Mysqli. PDO being preferred out of the two.
Your example can be come a set of very consise statements with PDO:
// create a connection this could be done in your connection include
$db = new PDO('mysql:host=localhost;dbname=your_db_name', $user, $password);
// for the first or only result
$infoArray = $db->query('SOME SQL')->fetch(PDO::FETCH_ASSOC);
// if you have multiple results and want to get them all at once in an array
$infoArray = $db->query('SOME SQL')->fetchAll(PDO::FETCH_ASSOC);
// if you have multiple results and want to use buffering like you would with mysql_result
$stmt = $db->query('SOME SQL');
foreach($stmt as $result){
// use your result here
}
However you should only use the above when there are now variables in the query. If there are variables they need to be escaped... the easiest way to handle this is with a prepared statement:
$stmt = $db->prepare('SELECT * FROM some_table WHERE id = :id');
$stmt->execute(array(':id' => $id));
// get the first result
$infoArray = $stmt->fetch(PDO::FETCH_ASSOC);
// loop through the data as a buffered result set
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
// do stuff with $row data
}