Error Using mysqli_data_seek when using Do While Procedure [duplicate] - php

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

Related

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

Check For Existing Table Using variable

I was wondering how to incorporate a variable into a PHP statement to check if a table exists. For some reason the query does not accept the variable. Here is what I have:
<?php
$servername = "localhost";
$username = "***";
$password = "***";
$dbname = "stavacom_students";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = "1";
echo $id;
$query101 = 'select 1 from "$id" LIMIT 1';
$val = mysqli_query($conn, $query101);
if($val !== FALSE){
echo "no";
} else {
?>
what?
<?php
};
?>
The statement needed a tilde around the variable. Here is the final statement:
$query101 = "select 1 from `$id` LIMIT 1";
You can implement this in two ways using mysql, the first one being a simple SELECT FROM type of query:
<?php
function mysql_table_exists(mysqli $conn, $table)
{
$res = #$conn->query('SELECT 1 FROM `' . $conn->real_escape_string($table) . '`');
if($res)
{
$res->free();
return true;
}
return false;
}
?>
You can also do this by performing a check in the INFORMATION_SCHEMA using the following statement:
SELECT 1 FROM information_schema.tables WHERE table_schema = '<database name>' AND table_name = '<table name>' LIMIT 1;
Lastly, you can call SHOW TABLES LIKE '<table name>'; and parse the results for a match, similar to the concept in the first example.
Use double quote("...Query...") Edit your query
$query101 = 'select 1 from "$id" LIMIT 1';
Into
$query101 = "select 1 from '".$id."' LIMIT 1";
OR
$query101 = "select 1 from $id LIMIT 1";
Change this, hope it work
$query101 = 'select 1 from "$id" LIMIT 1';
to this
$query101 = 'select 1 from "'.$id.'" LIMIT 1';

Select Query with OOP PHP ORM

for a customer I have to make little adjustments to an application what is build on OOP PHP. I have no experience at all with OOP, and normally I only use PHP for small functions. I would like to select data from my database, to use it in a build function and variable. My code under will explain
public function readTwitter(){
$accounts = array();
$hastags = array('coldplay');
\ORM::for_table('feed_items')->where('portal_reference', 'tw')->delete_many();
foreach($accounts as $account) {
$feed = $this->twitter->getFeedByAccount($account);
foreach($feed as $post){
$this->twitter->savePost($post);
}
}
foreach($hastags as $hashtag) {
$feed = $this->twitter->getFeedByHashtag($hashtag);
foreach($feed->statuses as $post){
$this->twitter->savePost($post);
}
}
}
So in this version of the application the foreach loop will check if the var is filled in, what is now done with an array, and use it in the function readTwitter() What I like to have is a select query which selects one specific row out of my database to use it instead of an array, written in my application as OOP as follow (written in procedural php):
$dbCon = mysqli_connect("localhost", "root", "root", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `questions` WHERE `location` = 'wall' ORDER BY `questions`.`id` DESC ";
$query = mysqli_query($dbCon, $sql);
if ($query) {
$row = mysqli_fetch_row($query);
$hashtags = $row[2]; //instead of array('coldplay');
}
public function readTwitter(){
$dbCon = mysqli_connect("localhost", "root", "root", "database");
if (mysqli_connect_errno()) {
echo "Failed to connect: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `vragen` WHERE `location` = 'wall' ORDER BY `vragen`.`id` DESC ";
$query = mysqli_query($dbCon, $sql);
if ($query) {
$row = mysqli_fetch_row($query);
$accounts = $row[3];
$hashtags = $row[2];
\ORM::for_table('feed_items')->where('portal_reference', 'tw')->delete_many();
$feed = $this->twitter->getFeedByAccount($accounts);
foreach($feed as $post){
$this->twitter->savePost($post);
}
$feed = $this->twitter->getFeedByHashtag($hashtags);
foreach($feed->statuses as $post){
$this->twitter->savePost($post);
}
}
}
I have tried to combine the code and it works like I want, but I dont think this is the right way for OOP, right?

php's mysqli_multi_query not working

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.

Getting the COUNT(*) value in 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;

Categories