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;
}
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);
}
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'];
I've been trying to execute a multiple query, so I've searched for a better approach on how to do this and I've read this mysqli_multi_query in php.
I tried it on my own to see the results, but it keeps on giving me error. Here's the code:
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '".$studid."'";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'";
if (mysqli_multi_query($conn, $sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
With the code above, it will just print error from the else statement I set. I also tried changing the second query to $sql .= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'"; and also tried putting semicolon after the first query to tell the SQL that I'm done with the first query since I'm putting 2 strings together, but still no luck.
try this
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '$studid';";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '$classcode'";
if ($conn->multi_query($sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
Make one query instead of two :
"SELECT ts.*, tc.*
FROM tbl_students as ts, tbl_classes as tc
WHERE ts.stud_id = '$studid'
AND tc.class_code = '$classcode'"
Note : If you get redundant data then use group by.
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
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;