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();
Related
I'm attempting to grab a number value from a mySQL database using PHP. I'd like to use that number value for some calculations after I've assigned it's value to a variable. The number value is stored as a float in my database. My code attempts to connect to my database (which it does successfully), then pull a number value based on parameters passed on by my query, then apply that number value to a variable that I can use in my code. In my code below, I'm simply trying to print that value to make sure it's pulling properly. The result I get is this notice: Notice: Array to string conversion in /Users/max/Desktop/Sites/webprojects/prg/nba/percentchange.php on line 14 Array
Here's my code:
$mysqli = new mysqli('localhost', 'root', 'root', 'NBA');
if (mysqli_connect_errno()) {
echo '<p>Error: could not connect to database.</p>';
exit;
}
$rank = "SELECT average FROM nbaCompRankings WHERE team = 'Celtics'";
$result = $mysqli->query($rank);
$currentRank = $result->fetch_assoc();
echo $currentRank;
The potential solutions I've found on this site use deprecated libraries, so I've been unsuccessful in a search for a solution. Thanks in advance for any help you can give!
Try This:
$result = $mysqli->query($rank);
while($row = $result->fetch_assoc()) {
$currentRank = $row["average"];
}
You should really be preparing your statements though.
$team = 'Celtics';
$sql= "SELECT average FROM nbaCompRankings WHERE team = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $team);
$stmt->execute();
$stmt->bind_result($average);
while($stmt->fetch()) {
$currentRank = $average;
}
$stmt->close();
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);
}
I'm trying to search a database using either a name OR a reference number (in the format ABC/X/012345/XX).
The name searches appear perfectly, as do reference number searches if I look for ABC or XX.
But if I search for the full reference number, no matches are found. The problem also happens with a partial reference number search containing more than one number (e.g. ABC/X/01 or even just 01).
I don't get an error message and the 'Sorry, your search returned no results' message isn't displayed, which would seem to suggest it's finding the correct entries, just not displaying them.
Can anyone spot where I'm going wrong? Thanks!
$search = $_POST['search'];
$search_term = "%".$search."%";
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH->prepare('SELECT user_id, name FROM users WHERE name LIKE :search_term OR ref_number LIKE :search_term');
$STH->bindParam(':search_term', $search_term, PDO::PARAM_STR);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
if ($STH->fetchColumn() > 0) {
while($row = $STH->fetch()) {
echo "<a href='viewprofile.php?user_id=".$row['user_id']."'>".$row['name']."</a><br/>";
}
} else {
echo '<p>Sorry, your search returned no results.</p>';
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
PDOStatement::fetchColumn($index = 0) fetches a whole row and returns the $indexth column's value. If you want to test how many rows your query returns, use PDOStatement::rowCount()
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
}
I have a database table made in phpmyadmin. I want the elements of the table to be stored row-wise in an array. I have three columns named edge_id, vertexA and VertexB. I want the elements of these three columns to be stored into an array.
I don't know those commands for PHP. Please help me out.
i have columns in my table named
"vertexa" and "vertexb",i want to
store the colums in two separate
arrays ...how can i do it??
The simplest way would be:
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
$vertices_a = array();
$vertices_b = array();
foreach($db->query('SELECT * from your_table_name') as $row){
$id = $row['edge_id'];
// add them to the proper array using the edge_id as the index -
// this assumes edge_id is unique
$vertices_a[$id] = $row['vertexa'];
$vertices_b[$id] $row['vertexb'];
}
So with PDO:
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
foreach($db->query('SELECT * from your_table_name') as $row){
echo $row['edge_id'];
echo $row['vertexA'];
echo $row['vertexB'];
}
Now if you need to use input data you need to escape it. The best way to do this is to use a prepared statement because escaping is handle when the parameters are bound to the query.
Lets say for example you want to use the edge_id supplied from a get request like mysite.com/show-boundry.php?edge=5...
$db = new PDO('mysql:host=localhost;dbname=your_db_name;', $user, $password);
// create a prepared statement
$stmt = $db->prepare('SELECT * from your_table_name WHERE edge_id = ?');
// execute the statement binding the edge_id request parameter to the prepared query
$stmt->execute(array($_GET['edge']));
// loop through the results
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
echo $row['edge_id'];
echo $row['vertexA'];
echo $row['vertexB'];
}
Also you shouldnt use mixed case column/table names like vertexA instead use underscore separators like vertex_a.
You first need to connect to the database:
$link = mysql_connect('localhost','username','password');
if (!$link) {
// Cannot connect
}
$ret = mysql_select_db('database-name', $link);
if (!$ret) {
// Cannot select database
}
Then you need to execute your query:
$ret = mysql_query('SELECT * FROM `table`;', $link);
if (!$ret) {
// Query failed
}
Then you simply load each row:
$data = array();
while ($row = mysql_fetch_assoc($ret)) {
$data[] = $row;
}
Then you should free your request results
mysql_free_result($ret);
And voilĂ .
$res = mysql_query("............");
$row = mysql_fetch_array($res);
Checkout: mysql_fetch_array PHP page