how to get last "shiftID" row entry in sql table mysqli - php

Hi i have a php form and part of this is to get the last "shiftID" row entry in my table and put this into a variable so i can later add 1 to said variable. However the result of the following code returns the information linked below. How do i get the last "shiftID" number by itself into a variable.
<?php
session_start();
include 'dbh.php';
$start = $_GET['starttime'];
$finish = $_GET['finishtime'];
$dat = $_GET['date'];
$id = $_GET['userid'];
$shiftidd = $conn->query("SELECT shiftID FROM shift_user ORDER BY shiftID DESC LIMIT 1");
$row = mysqli_fetch_row($shiftidd);
echo print_r($row[0]);
//$result = $conn->query("INSERT INTO shift (shiftStart, shiftFinish, shiftDate)
//VALUES ('$start', '$finish', '$dat')");
//$sql = $conn->query("INSERT INTO shift_user (shiftID, userID) VALUES ('$shiftidd', '$id')");
//header("Location: shifts.php");
?>
Web page result:
"connected 41"
I'm looking for the number "4" but I'm guessing the "1" is the affected row along with the result? but how do i get rid of the "1"?
Thanks in advance.

1 is a result of print_r() which is superfluous here. Use either echo or print_r, but not both

You can do it like. After you insert query executed use the following function
mysql_query("INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
$id = mysql_insert_id();//will return you the last id inserted into table//
But if you want to find the last id of some table then you have to use the follwoing code:
$shiftidd = $conn->query("SELECT MAX(shiftID) FROM shift_user LIMIT 1");
$row = mysqli_fetch_row($shiftidd);
echo print_r($row[0])///////it will be the last id of the table////////
if you want to find next id please try this
$shiftidd = $conn->query("SELECT MAX(shiftID)+1 FROM shift_user LIMIT 1");
$row = mysqli_fetch_row($shiftidd);
echo print_r($row[0])///////it will be the next id of the table///////////

Related

Output is array, how to fix this?

Right now I am selecting some data from Mysql which I want to echo out, but I don't know how..
Code
<?php
// Database connection
require_once($_SERVER["DOCUMENT_ROOT"] . "/includes/config.php");
require_once($_SERVER["DOCUMENT_ROOT"] . "/includes/opendb.php");
// News 1
$searchroutenews1 = "SELECT newsid FROM NewsHomepage WHERE id = '1'";
$handlenews1 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews1);
$news1 = mysqli_fetch_row($handlenews1);
$searchroutenewsimg1 = "SELECT newsimg FROM NewsHomepage WHERE id = '1'";
$handlenewsimg1 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg1);
$NewsImg1 = mysqli_fetch_row($handlenewsimg1);
// News 2
$searchroutenews2 = "SELECT newsid FROM NewsHomepage WHERE id = '2'";
$handlenews2 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews2);
$news2 = mysqli_fetch_row($handlenews2);
$searchroutenewsimg2 = "SELECT newsimg FROM NewsHomepage WHERE id = '2'";
$handlenewsimg2 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg2);
$NewsImg2 = mysqli_fetch_row($handlenewsimg2);
// News 3
$searchroutenews3 = "SELECT newsid FROM NewsHomepage WHERE id = '3'";
$handlenews3 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenews3);
$news3 = mysqli_fetch_row($handlenews3);
$searchroutenewsimg3 = "SELECT newsimg FROM NewsHomepage WHERE id = '3'";
$handlenewsimg3 = mysqli_query($GLOBALS["___mysqli_ston"], $searchroutenewsimg3);
$NewsImg3 = mysqli_fetch_row($handlenewsimg3);
?>
After this I require_once this in an other file, and then I echo the variables $news1, $news2, $news3, $NewsImg1, $NewsImg2 and $NewsImg3. But if I echo this variables out now it says: array.
You can fetch all this information via a single query, instead of the 6 you currently are running. Then it's a matter of putting mysqli_fetch_*() as the argument of a while, as you'll then fetch all the rows, until that function returns null - at which point you've fetched all the rows returned by the query.
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT newsid, newsimg FROM NewsHomepage WHERE id IN (1, 2, 3)");
while ($row = mysqli_fetch_assoc($result)) {
echo $row['newsid']." ".$row['newsimg'];
}
Change however you need it to be displayed inside the while loop, and use the two variables as they are inside.
Alternatively, you can use WHERE id BETWEEN 1 AND 3 instead, but using IN (1, 2, 3) can more easily be changed to the exact ids you need.
http://php.net/mysqli-result.fetch-assoc
First you should read http://php.net/manual/en/mysqli-result.fetch-row.php
you can find there mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an enumerated array mysqli_fetch_row always return array so now you can't echo array thats why it gives you array.
You can try foreach loop or for loop or while loop to display your data. there are also various methods to get array value.
Below is an example you can use.
while ($news1 = mysqli_fetch_row($handlenews1)) {
echo $news1[0];
}

incorrect result display from database

I have a database table that has 4 records with a column _id that auto increments. When I run a query to get all records, it works but it doesn't echo out all the ids, it only points to the first rows and echos it four times. I am using PHP and MySQLi. Here is my code
Code for querying
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
Code for display
do{
echo result['_id'];
}while($query->fetch_assoc());
It outputs 1111 instead of 1234. Please what is wrong?
You're fetching each of the 4 results, so it loops the appropriate number of times; but you're only assigning the fetched result to $result once, so that's the only _id value that gets echoed
do{
echo $result['_id'];
}while($result = $query->fetch_assoc())
You also can use a foreach loop :
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
foreach($result as $data){
echo $data['_id'];
}

Getting last value of a field in mysql

I am trying to get the last value of a field during a new registration.
before insert data into the table, I want to create a user id number according to the last registered user's id number. to do that I use this:
//to reach the last value of userID field;
$sql = "SELECT userID FROM loto_users ORDER BY userID DESC LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$value = $row['userID'];
echo "$value"; //not resulting here
}
$userID = $value+1;
so, the userID becomes 1.
The weird thing is, I could capable to use exact same code in another php file and works fine.
I would like to say that, rest of the code works fine. No problem with db connections or any other things you can tell me.
Note that: When I run the same query line in the mysql interface, I can get the value I want. I mean $sql line.
Your problem is in this code:
{
$svalue = $row['userID'];
----^
echo "$value"; //not resulting here
}
$userID = $value+1;
Change to $value.
But the right answer is to define userID to be auto-incrementing. That way, the database does the work for you. After inserting the row, you can do:
SELECT LAST_INSERT_ID()
To get the last value.
I solved the problem. Here;
$sql = "SELECT userID FROM loto_users ORDER BY userID DESC LIMIT 1";
$result = mysql_query($sql);
$user_info = $result->fetch_assoc();
$value = intval($user_info["userID"]);
$userID = $value+1;
Thanks everyone.
If you mark the userID field as autoincrement in you mysql table.
You won't need to set the userID and db increase the userID for you. You can get the assigned userID using the mysql_insert_id() function. Here is an example from php.net
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Here is another example for your case
mysql_query("INSERT INTO 'loto_users'('username',...) values('usernameValue',...)");
echo "New User id is ".mysql_insert_id();

Get total number of records for a given day in Highcharts and PHP

I'm trying to get my highcharts chart working and I'm almost there.. I just have one little problem: I need that the value will be the total count of the records at the same day but I'm kinda confused with my code now and the chart is totally messed up..
Here is the code that pulls the data:
<?php
header("Content-type: text/json");
include('../includes/config.php');
$tablename = "analytics";
$result = mysql_query("SELECT COUNT(*) AS count FROM $tablename");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$sql = "SELECT id, date FROM $tablename ORDER BY date";
$result = mysql_query( $sql ) or die("Couldn't execute query.".mysql_error());
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row['id'] = (int) $row['id'];
$rows[$i] = array(strtotime($row['date'])*1000, $row['id']);
$i++;
}
echo json_encode($rows);
?>
If it will help here is my database values:
insert into `analytics`(`id`,`user`,`item`,`ip`,`country`,`date`) values
(10,1,1,'127.0.0.1','','2011-12-17 06:41:51'),
(11,1,1,'127.0.0.1','','2011-12-17 06:42:23'),
(12,1,1,'127.0.0.1','','2011-12-17 06:43:07'),
(13,1,1,'127.0.0.1','','2011-12-17 06:44:19'),
(14,1,1,'127.0.0.1','','2011-12-17 06:44:21'),
(15,1,1,'127.0.0.1','','2011-12-17 06:44:22'),
(16,1,1,'127.0.0.1','','2011-12-17 06:44:49'),
(17,1,1,'127.0.0.1','','2011-12-17 06:46:59'),
(18,1,1,'127.0.0.1','','2011-12-17 06:47:20'),
(19,1,1,'127.0.0.1','','2011-12-17 06:47:35'),
(20,1,1,'127.0.0.1','','2011-12-17 06:47:42'),
(21,1,1,'127.0.0.1','','2011-12-17 06:48:07'),
(22,1,1,'127.0.0.1','','2011-12-17 06:48:14'),
(23,1,1,'127.0.0.1','','2011-12-17 06:48:29'),
(24,1,1,'127.0.0.1','','2011-12-18 06:49:10'),
(25,1,1,'127.0.0.1','','2011-12-19 07:05:45'),
(26,1,1,'127.0.0.1','','2011-12-20 08:11:32'),
(27,1,1,'127.0.0.1','','2011-12-21 08:26:45'),
(28,1,1,'127.0.0.1','','2011-12-17 08:44:34');
And here is the final result:
I totally lost my self here, can someone help?
EDIT: did what #ajreal said and here is the output:
This is the query to get count for each date
SELECT date, COUNT(*) AS count
FROM $tablename
GROUP BY date;
You can use this query to replace your first query.
And to a loop (like your second query), set $total += $row["count"] to get a grand total like your original first query does

count syntax in mysql

I would like to get the number of rows that satisfies the condition.
mysql_query("SELECT COUNT(*) FROM sid WHERE sid='".session_id()."'");
this one ignores the condition.
update:
$session = session_id();
$sql = "SELECT COUNT(*) as row_count FROM sid WHERE sid = '$session' ";
var_dump($r = mysql_query($sql));//resource(4) of type (mysql result) (1)
var_dump(mysql_fetch_assoc($r));
//array(1) { ["row_count"]=> string(1) "1" } - this result is OK(2)
(1) resource(4) - I thought that 4 was the count
(2) mysql_real_escape_string($_SESSION['id']); gives 0
note:
I have changed from mysql_num_rows to this type of getting count because I thought it will return immediately the count and I dont have to write more lines to get this basic data.
The correct way of doing this is:
$session = mysql_real_escape_string($_SESSION['id']); <<-- Get the session id
echo "debug: session_id = ".htmlentities($session);
$sql = "SELECT count(*) as row_count FROM tablename WHERE sid = '$session' ";
$result = mysql_query($sql);
if (!$result) {
die('error in query '.$sql.' error is: '.mysql_error());
}
//we only have 1 result
$row = mysql_fetch_array($result);
//always sanitize so you don't suffer XSS attacks when the query changes
//and the $row['x'] changes from an integer to a user-supplied string.
$count = intval($row['row_count']);
echo "count is: ".$count;
The table name and the column name can be the same, but in your case they probably are not.
sid obviously stands for the field "session_id", so you need to replace the first sid after FROM with your tablename.
table name = "sessions"
column name = "sid"
mysql_query("SELECT COUNT(*) FROM sessions WHERE sid='".session_id()."'");
first write your query in php variable and echo it to check what session_id() returns and then try may be there is nothing in your session_id(); like
$sql = "SELECT COUNT(*) FROM sid WHERE sid='".session_id()."'";
echo $sql;
and run it in phpmyadmin if it work than your query is qrite else something is wrong

Categories