Select query slow to update - php

This is probably a simple error, but I'm stumped...
I have a database that has entries inserted using AJAX on a chrome extension, which works great and inserts instantly.
I have a separate PHP file that is being used to output the number of entries in a table. This works, but is takes a long time for the entries to update to the right number when called. I need it to be up to date instantly.
Is there any reason why it's taking so long for the query to output the correct number, when the table itself is updating instantly?
<?php
$link = mysqli_connect("localhost", "root", "", "fyp");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = mysqli_query($link, "SELECT * FROM links")) {
$row_cnt = mysqli_num_rows($result);
printf($row_cnt);
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>
Thanks.

I think you should simple run:
if ($result = mysqli_query($link, "SELECT count(*) AS `nr` FROM links")) {
$row_cnt = mysqli_fetch_assoc($result);
printf($row_cnt['nr']);
mysqli_free_result($result);
}
It will be the best one. Or if your links are not removed at all you could run:
if ($result = mysqli_query($link, "SELECT id FROM links ORDER BY id DESC LIMIT 1")) {
$row_cnt = mysqli_fetch_assoc($result);
printf($row_cnt['id']);
mysqli_free_result($result);
}

Hand off the processing to the database by using an aggregate query and return a scalar result with mysqli_result:
if ($result = mysqli_query($link, "SELECT COUNT(1) FROM links")) {
$row_cnt = mysqli_result($result, 0);
printf($row_cnt);
mysqli_free_result($result);
}

Related

Mysqli select and count by

i have the following code. When i run into phpmyadmin the result returns correctly 9 rows of users and a column called |count(*) with the count next to each user. Whats wrong on my while and cant return me the count? It returns just the user when in php code
<?php
if ($result = $mysqli->query("SELECT n.user, count(*) AS count_user FROM metadata n group by n.user")) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
printf ($row['user'], $row[count]);
}
}
/* free result set */
?>
hi if i understand correctly your Question try this :
<?php
$mysqli = new mysqli("localhost", "root", "root", "test");
if (mysqli_connect_errno()) {
printf("Échec de la connexion : %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT name FROM users ORDER BY name")) {
/* get num rows */
$row_cnt = $result->num_rows;
while($row = mysqli_fetch_assoc($result)) {
printf($row['name']);
}
printf('Nombre of line %s',$row_cnt);
$result->close();
}
$mysqli->close();
You have used wrong index. you gave alias count_user in your query so you must use it when you fetch.
Just change this
printf ($row['user'], $row[count]);
to
printf ($row['user'], $row['count_user']);

How to delete records in a table with JSON

I have a JSON file that brings data in to iOS. I also want it to see if there are more than 2 records.
If there is more than 2 records i want it to delete everything apart from the last 2 records
How do I insert this in to this php file
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM test ORDER BY id DESC LIMIT 1";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
You are using LIMIT 1 which will mean you only get 1 record back. Are you planning on increasing the limit?
You could always use the PHP count() function and the array_slice() function if you need to cull down an array of records returned...
http://php.net/array_slice

i want to execute a saved query in the database

I want to execute a query that i saved in my database like this:
ID | NAME | QUERY
1 | show_names | "SELECT names.first, names.last FROM names;"
2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"
Is this possible ?
I am kinda noob in php so plz explain if it is possible.
If I understand you correctly, you have your queries saved in the database in a table and you want to execute those.
Break the problem down: you have two tasks to do:
Query the database for the query you want to run.
Execute that query.
It's a bit meta, but meh :)
WARNING: the mysql_ functions in PHP are deprecated and can be dangerous in the wrong hands.
<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
die('Could not select database');
}
$name = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
die("DB Error, could not query the database\n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>
if you did create a stored procedure/function you can simply use:
mysql_query("Call procedure_name(#params)")
Thats will work. reference here: http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Querying the table to get the query, then executing that query and looping through the results and outputting the fields
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result))
{
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $row['QUERY']);
while ($row2 = mysqli_fetch_assoc($result))
{
foreach($row2 AS $aField=>$aValue)
{
echo "$aField \t $aValue \r\n";
}
}
}
?>
just open the Table and get the individual query in a variable like
$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
$query = $row['Query'];
mysql_query($query); // The Query from the Table will be Executed Individually in a loop
}
if you want to execute a single query from the table, you have to select the query using WHERE Clause.

php echo data from certain id

EDIT: I'm sorry I was unclear, I try to explain it right this time.
I have this data in a database table called tMenu:
id page_nl text
1 index_1 index1_text
2 index_2 index2_text
3 index_3 index3_text
These are 3 pages on my website called (in this case) index_1, index_2 and index_3. I have programmed it is such a way that each page shows there index1_text.
What I want now is to show page_nl in a menu. The code I have now is:
$qh = mysql_query('SELECT id, page_nl FROM tMenu ORDER BY id');
$row = mysql_fetch_array($qh);
$id = 'id';
<? echo $row['page_nl']; $id=="1" ;?>
<? echo $row['page_nl']; $id=="2" ;?>
<? echo $row['page_nl'];?>
In the way it is now it shows only page_nl from id 1, but I want that the next link shows page_nl from id 2. I hope my question is more clear now.
Your question isn't very clear - are you asking for something like this
$sql = "select * from yourtable where id = 1";
$result = mysql_query($sql);
//I am assuming there are more than 1 rows for ID 1
while($row = mysql_fetch_assoc($result)) {
echo $row['page_nl'];
}
OR ============================
$sql = "select * from yourtable"; //Select All
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
if($row['id'] == 1)
{
echo $row['page_nl'];
}
}
Presuming you mean database table, you need a routine to connect to the database then fetch the info:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "databasename"); // database name
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM table_name"; // put table name here
$result = $mysqli->query($query);
/* numeric array */
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["id"], $row["page_nl"]);
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
?>
You need to use a foreach($var as $key =>$value) loop

MySQL - count total number of rows in php

What is the best MySQL command to count the total number of rows in a table without any conditions applied to it? I'm doing this through php, so maybe there is a php function which does this for me? I don't know. Here is an example of my php:
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("some command");
$row = mysql_fetch_array($result);
mysql_close($con);
?>
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("select count(1) FROM table");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>
Either use COUNT in your MySQL query or do a SELECT * FROM table and do:
$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";
mysqli_num_rows is used in php 5 and above.
e.g
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
Use COUNT in a SELECT query.
$result = mysql_query('SELECT COUNT(1) FROM table');
$num_rows = mysql_result($result, 0, 0);
you can do it only in one line as below:
$cnt = mysqli_num_rows(mysql_query("SELECT COUNT(1) FROM TABLE"));
echo $cnt;
use num_rows to get correct count for queries with conditions
$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";
for PHP 5.3 using PDO
<?php
$staff=$dbh->prepare("SELECT count(*) FROM staff_login");
$staff->execute();
$staffrow = $staff->fetch(PDO::FETCH_NUM);
$staffcount = $staffrow[0];
echo $staffcount;
?>
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo "number of rows: ",$rowcount;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
it is best way (I think) to get the number of special row in mysql with php.
<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>
Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php
$sql = "select count(column_name) as count from table";
Well, I used the following approach to do the same: I have to get a count of many tables for listing the number of services, projects, etc on the dashboard. I hope it helps.
PHP Code
// create a function 'cnt' which accepts '$tableName' as the parameter.
function cnt($tableName){
global $conection;
$itemCount = mysqli_num_rows(mysqli_query($conection, "SELECT * FROM `$tableName`"));
echo'<h6>'.$itemCount.'</h6>';
}
Then when I need to get the count of items in the table, I call the function like following
<?php
cnt($tableName = 'projects');
?>
In my HTML front end, so it renders the count number
It's to be noted that I create the cnt() function as a global function in a separate file which I include in my head, so I can call it from anywhere in my code.

Categories