I'm using to following to count the number of rows in a table:
// Count rows
$sql = "SELECT COUNT(*) FROM articles";
$result = mysqli_query($con,$sql);
$max = mysqli_fetch_row($result);
echo $max;
This echoes array. I understand why but I can't find how to get the value in this case. I've tried $max[0]. I don't understand how to reference the column in the array in this case.
try this:
$sql = "SELECT COUNT(*) as counts FROM articles";
$result = mysqli_query($con,$sql);
$max = mysqli_fetch_assoc($result);
echo $max['counts'];
some docs here
EDIT:
$sql = "SELECT COUNT(*) as counts FROM articles";
$result = mysqli_query($con,$sql);
while($max = mysqli_fetch_assoc($result))
{
echo $max['counts'];
}
You should use MySQL PDO.
Try this:
try{
$conn = new PDO("mysql:host=localhost;dbname=dbname", username, password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
$errors = "There is no connection to the Server: localhost";
}
$qry = $conn -> prepare("SELECT COUNT(*) AS counts FROM articles");
$qry -> execute();
while($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$Total = $row['counts'];
}
echo $Total;
Related
I cannot get my Mysqli queries to both work. If I comment out one function in my html, the other function is properly executed and vice versa.
function all_posts() {
require_once 'database.inc.php';
$mysqli = mysqli_connect($host, $username, $password, $database);
$query = mysqli_query($mysqli, "SELECT variable_name, post_name, post_date, post_display FROM blog_posts ORDER BY id DESC LIMIT 5");
if (!$query)
echo mysqli_error();
while ($results = mysqli_fetch_assoc($query)) {
$post_name = $results['post_name'];
$post_date = $results['post_date'];
$post_display = $results['post_display'];
$variable_name = $results['variable_name'];
echo "<a href='posts.php?post={$variable_name}'>";
echo "<div class='entry'>";
echo "<div class='entry_header'>";
echo "<h2>{$post_name}</h2>";
echo "<h3>{$post_date}</h3>";
echo "</div>";
echo "<p>{$post_display}</p>";
echo "</div>";
echo "</a>";
}
mysqli_free_result();
}
function all_sidebar_posts() {
require_once 'database.inc.php';
$mysqli = mysqli_connect($host, $username, $password, $database);
$query = mysqli_query($mysqli, "SELECT variable_name, post_name FROM blog_posts ORDER BY id DESC LIMIT 5");
while ($results = mysqli_fetch_assoc($query)) {
$post_name = $results['post_name'];
$variable_name = $results['variable_name'];
echo "<li><a href='posts.php?post=$variable_name'>$post_name</a></li>";
}
mysqli_free_result();
}
Here is the html that I am outputting to.
<ul>
<?php all_sidebar_posts(); ?>
</ul>
</div>
<div class="content_container">
<?php all_posts(); ?>
</div>
I have tried using mysqli_data_seek(); but haven't had luck. Perhaps I am not using it right? I have browsed many questions and found similar ones but I have tried them all to no avail. I am new to programming so I may be overlooking something basic. Thank you all for the help!
You are doing it wrong way.
Never mix your data manipulation code with presentation code.
First, get the posts into array:
require_once 'database.inc.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect($host, $username, $password, $database);
$sql = "SELECT variable_name, post_name, post_date, post_display
FROM blog_posts ORDER BY id DESC LIMIT 5"
$result = mysqli_query($mysqli, $sql);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
and then use this $data array to display posts any times you need, simply using foreach()
http://www.php.net/manual/en/mysqli-result.data-seek.php
Consult the manual for the usage of data_seek();
Take this example:
$Query = "SELECT * FROM Users WHERE ID='1'";
$TheQuery -> $MySQLi->query($Query);
$Results = $TheQuery->fetch_array(MYSQLI_ASSOC);
$TheQuery->data_seek(0); // Lets you re-use the query
$Count = $TheQuery->num_rows; // Gets the count
so in your case:
You should perform the procedure method:
$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
if ($result = mysqli_query($link, $query)) {
/* fetch row */
$row = mysqli_fetch_row($result);
printf ("City: %s Countrycode: %s\n", $row[0], $row[1]);
mysqli_data_seek($result, 0);
$row_cnt = mysqli_num_rows($result);
/* free result set*/
mysqli_free_result($result);
}
Using count() query with php will cause the result display in looping. How to fix this issue?
phpmyadmin has no problem showing the sum but can't apply it to php code.
$conn = mysqli_connect('localhost','root','','db');
if (!$conn) { die('db error'); };
$result = mysqli_query($conn, '
select count(*) as x from users
');
$row = mysqli_fetch_assoc($result);
echo $row['x'];
Expect result :
2
Actual output :
2222222222222222222222222222222222222222222222222222222222222222222...
I recommend you to use prepared statements.
$conn = new mysqli("localhost", "root", "", "db");
if($stmt = $conn->prepare("SELECT count(*) as x FROM users")) {
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$number = $row['x'];
}
$stmt->close();
}else{
echo "Error";
}
$conn->close();
if(isset($number)){
echo $number;
}
I have over 40'000 entries and each is assigned to a "list_name"
I am basically trying to get just the list_name value echo'd out
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
$groupr = mysqli_fetch_assoc($groupq);
do {
echo $groupr['list_name'];
} while($groupr = mysqli_fetch_assoc($groupq));
however its only displaying 1 entry then no more ..
https://imgur.com/a/3rnXGet
Try this.
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
while($groupr = mysqli_fetch_assoc($groupq)){
echo $groupr['list_name'];
}
$database = "sample" //replace your database name here
$conn=new mysqli("localhost","root","",$database); // here username is root and password is null , change it according to yours
if($conn->connect_error)
{
echo $conn->connect_error;
die("sorry database connection failed");
}
$sql = "SELECT * FROM products-full GROUP BY list_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row['list_name'];
}
}
thats it
try this
$groupq = mysqli_query($dbc, "SELECT list_name, count(*) FROM `products-full` GROUP BY
`list_name`");
while($groupr = mysqli_fetch_assoc($groupq)) {
echo $groupr['list_name'];
}
<?php
require("config.inc.php");
$query = "Select 1 FROM dogs WHERE dog_id = :iddog ";
$query_params = array(':iddog'=> $_POST['iddogPHP2']);
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$dono2 = $result ->fetchColumn(1);
$raca2 = $result ->fetchColumn(2);
$sex2 = $result ->fetchColumn(3);
$estado2 = $result ->fetchColumn(4);
$query = "Select * FROM dogs WHERE dispon = 'Sim' AND dono != '$dono2' AND estado = '$estado2' AND raca = '$raca2' AND sex != '$sexo2' ";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
?>
This is my code and the problem is that the variables dono2, raca2, gender2 are not getting the values from the database. What's wrong in it?
Instead of SELECT 1 you need to use SELECT * in your first query.
$query = "Select * FROM dogs WHERE dog_id = :iddog ";
The following returns an array of results
$rows = $stmt->fetchAll();
So you would need to specify which one to reference.
$dono2 = $rows[0]['dono'];
$raca2 = $rows[0]['raca'];
$sexo2 = $rows[0]['sex'];
$estado2 = $rows[0]['estado'];
$rows = $stmt->fetchAll();
fetch all rows from database you need to specify which row you want if it's multiple row
$dono2 = $rows[0]['dono'];
$raca2 = $rows[0]['raca'];
$sexo2 = $rows[0]['sex'];
$estado2 = $rows[0]['estado'];
Try this code
$stmt = $db->prepare($query);
$stmt->bindParam(':iddog', $_POST['iddogPHP2']);
$stmt->execute($query_params);
$dono2 = $stmt ->fetchColumn(1);
$raca2 = $stmt ->fetchColumn(2);
$sex2 = $stmt ->fetchColumn(3);
$estado2 = $stmt ->fetchColumn(4);
I have multiple record(s) in PHPMYADMIN and now i am trying to fetch those record(s) using PHP Code, but always i am getting Array ( ) 1 whenever i run my php script using Localhost, however i have 5 rows in table.
Please see below code:
<?php
$objConnect = mysql_connect("localhost","root","");
$objDB = mysql_select_db("mydatabase");
$strMemberID = $_POST["sMemberID"];
$strSQL = "SELECT * FROM order_details WHERE
MemberID = '".mysql_real_escape_string($strMemberID)."' ORDER BY OrderID DESC ";
$objQuery = mysql_query($strSQL);
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr = array();
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
mysql_close($objConnect);
echo print_r($arr);
?>
change your code in while loop.
declare $arr outside the loop. declaring array inside loop will clear it before initializing. thats why you are getting a single row in each run.
$arr = array();
while($obResult = mysql_fetch_assoc($objQuery))
{
$arr["OrderID"] = $obResult["OrderID"];
$arr["ItemDetails"] = $obResult["ItemDetails"];
}
Also, to view array elements use echo json_encode($arr) or var_dump($arr) or print_r($arr);
it will definitely work for you
It's not directly an answer to your question but while you're at it try to use PDO and prepared statements
$strMemberID = $_POST["sMemberID"];
$strSQL = 'SELECT * FROM order_details WHERE MemberID = ? ORDER BY OrderID DESC';
try {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->prepare($strSQL);
$query->execute(array($strMemberID));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo 'Exeption: ' .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
var_dump($result);
You may like it.