Echo count in php - php

I would like to ask how to echo the count from sql in php?
$sql = $conn->query("SELECT count(*) as total FROM visitor");
$row = mysql_fetch_array($sql);
Echo $row['total'];

First of all do not mix mysql_ and mysqli extension together, you can't get anything by doing this.
Second, very important, mysql_ is deprecated and closed in PHP 7, you can use mysqli_ or PDO.
Here is the basic example with MYSQLi Objected Oriented:
<?php
// Create connection
$conn = new mysqli($YourServerName, $Yourusername, $Yourpassword, $Yourdbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT COUNT(*) AS Total FROM Table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_row();
echo 'Total:'. $row[0]; // print total record
}
else
{
// if record not exist.
}
?>

$row = $conn->query($sql);
$data = $row->fetch();
echo $data['total'];

Related

Error Using mysqli_data_seek when using Do While Procedure [duplicate]

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);
}

When row is empty in PHP it should not display anything. When there is something in it, it should display input

function getConnection() {
$con = new mysqli('localhost','root','','shop');
if($con->connect_errno!=0){return null;};
$con->query("SET NAMES utf8");
return $con;}
function getRed(){
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
if($row["red"] == ""){
echo "";
}else{
while($row = mysqli_fetch_assoc($result)){
echo "<input type='image' src=" . $row["red"]. ">";
}
mysqli_close($con);}}
In PHP I have row "red" filled with link to MShirt/redshirt.png. This code should create an input with this image but if is empty shouldn't create input. Now, this doesn't work even with a filled row.
You have a number of problems with your code, but the main one is that mysqli_num_rows() does not return data. It tells you how many records were fetched from the database into PHP.
You don't need mysqli_num_rows() in your code.
You don't need mysqli_close($con);, especially not inside of the loop.
You don't need the while loop. This is an old way of iterating. Use foreach instead.
You don't need if/else and echo "". You only need the positive condition.
Here is your code fixed:
function getConnection() {
// enabler error reporting, create an instance and set the correct charset
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli('localhost', 'root', '', 'shop');
$con->set_charset('utf8mb4');
return $con;
}
function getRed() {
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = $con->query($sql);
foreach ($result as $row) {
if ($row["red"] != "") {
echo "<input type='image' src=" . $row["red"] . ">";
}
}
}
The function mysqli_num_rows() returns only the count of results returned by your query, the mysqli_fetch_assoc() is the one going through the results. I would suggest taking the mysqli_close($con); outside the if statement as shown.
<?php
function getConnection() {
$con = new mysqli('localhost','root','','shop');
if($con->connect_errno!=0){return null;};
$con->query("SET NAMES utf8");
return $con;}
function getRed(){
$con = getConnection();
$sql = "SELECT red FROM colors;";
$result = mysqli_query($con, $sql);
$rowCount = mysqli_num_rows($result);
if($rowCount > 0) {
while($row = mysqli_fetch_assoc($result)){
if(isset($row["red"]) && $row["red"] != "") {
echo "<input type='image' src=" . $row["red"]. ">";
}
}
}
mysqli_close($con);
}
I don't know what this input should work for, but I assume you want to simply embed an image. Use it like this:
$result = mysqli_query($con, $sql);
while ($row= mysqli_fetch_assoc($result)) {
echo '<img src="' . $row['red']. '" />';
}
mysqli_num_rows is used to count how many rows are in the result, it returns the number of rows which you can not read like an array...
$result = mysqli_query($con, $sql);
$row_count = mysqli_num_rows($result);
echo $row_count.' rows in result.';
while ($row = mysqli_fetch_assoc($result)) {
echo '<img src="' . $row['red']. '" />';
}
Please make sure to understand basic HTML before getting into PHP and MySQL, also do not do database queries without getting to know proper security standards.

React Native fetch data in MYSQL database

I'm using React Native and extracting data from MYSQL. But I can't get the direct result of my data. So the output that is now: "[{" STT_TIP ":" Taxi "}]", I would say that the output: "Taxi" get. So just give me the result. He's drawing his name in the painting I'm taking now. I just want to draw the result.
<?php
include 'DBConfig.php';
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
mysqli_query($conn, "SET CHARACTER SET 'utf8'");
mysqli_query($conn, "SET SESSION collation_connection ='utf8_turkish_ci'");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$arr = array();
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$email = $obj['email'];
$password = $obj['password'];
$Sql_Query = "select STT_TIP from ...... where .. = '$email' and . = '$password' ";
$result = $conn->query($Sql_Query);
if ($result->num_rows > 0) {
while ($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
}
echo $json;
$conn->close();
?>
Since you said this only returnn 1 result. Don't bother with the loop
use
$row = $result->fetch_assoc(); // same as mysqli_fetch_assoc($result)
and
$json = json_encode($row['STT_TIP');
Will return the same as plain text(no brace, nor object)
Be carefull, your code is vulnerbale to SQL injection.

php-mysql count() query repeating results

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;
}

Getting Data From Multiple MySQL Tables Using PHP and mysqli

I am trying to draw data from multiple tables that have been indexed to relate to one another. I ran this query in MySQLWorkbench, and it ran successfully. However when I tried to run a PHP test, nothing showed up, not even for the first field. Here is my code:
<?php
$db = new mysqli('host', 'user', 'password', 'database');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "
SELECT
`Contact`.`firstName`,
`Contact`.`lastName`,
`ssn`.`ssn`,
`Contact`.`country`,
`Allergies`.`allergy`,
`Allergies`.`allergyType`,
`Allergies_Contact`.`allergyNotes`,
`CurrentPrescriptions`.`prescriptionName`,
`CurrentPrescriptions`.`prescribedDate`,
`BloodType`.`bloodType`
FROM
`database`.`Contact`,
`database`.`Allergies_Contact`,
`database`.`Allergies`,
`database`.`ssn`,
`database`.`CurrentPrescriptions`,
`database`.`BloodType`
WHERE
`Contact`.`contactKey` = `Allergies_Contact`.`contactKey`
AND `Allergies`.`allergiesKey` = `Allergies_Contact`.`allergiesKey`
AND `ssn`.`contactKey` = `Contact`.`contactKey`
AND `CurrentPrescriptions`.`contactKey` = `Contact`.`contactKey`
AND `BloodType`.`contactKey` = `Contact`.`contactKey`;
";
$result = $db->query($query) or die($db->error.__LINE__);
if ($result = mysqli_query($db, $query)) {
while ($row = mysqli_fetch_row($result)) {
print(row[0]);
}
mysqli_free_result($result);
}
mysqli_close($db);
?>
Please tell me what I am doing wrong here, because from what I can see its formatted correctly.
Several things:
1.- You have two query sentences, change:
$result = $db->query($query) or die($db->error.__LINE__);
if ($result = mysqli_query($db, $query)) {
With this
$result = $db->query($query) or die($db->error.__LINE__);
if ($result !== false) {
2.- Yo made a mistake when trying to print the variable, change:
while ($row = mysqli_fetch_row($result)) {
print(row[0]);
}
With this
while ($row = mysqli_fetch_row($result)) {
print($row[0]); // You missed a $
}
<?php
//conection:
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
//consultation:
$query = "SELECT name FROM mytable" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
//display information:
while($row = mysqli_fetch_array($result)) {
echo $row["name"] . "<br>";
}
?>
http://php.net/manual/en/function.mysqli-connect.php

Categories