I have search some resources, but I still unable to make it. I would like to retrieve the data from the max id. I have some codes in .php to make query
<?php
$DB_HostName = "mysql8.000webhost.com";
$DB_Name = "";
$DB_User = "";
$DB_Pass = "";
$DB_Table = "";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$query = "SELECT MAX(id),recommendData,room,level FROM $DB_Table";
$res = mysql_query($query,$con) or die(mysql_error());
mysql_close($con);
$rows = array();
while ($r = mysql_fetch_assoc($res))
{
$row["maxid"] = array(
"level" => $r["level"],
"recommendData" => $r["recommendData"],
"room" => $r["room"],
"id" => $r["MAX(id)"]
);
}
header('Content-type: application/json');
echo json_encode($row);
die;
?>
the result shows like this:
{"maxid":{"level":"2","recommendData":"8","room":"4F","id":"4"}}
the the id is right, but data of level, recommendData, room are from the first id. Do I make something wrong??
You can try
$query = "SELECT id,recommendData,room,level FROM $DB_Table ORDER BY id DESC LIMIT 1";
Because currently you are fetching the max id plus the other info
--
Please do not use mysql_* functions.
Use MySQLi or PDO instead
You can read on why more here
The right way to do the query is:
SELECT id, recommendData, room, level
FROM $DB_Table
ORDER BY id desc
LIMIT 1;
That is, don't do an aggregation at all.
Related
I have one problem.I am fetching some data from MYSQL table.But there are some duplicate datas. I need to skip those duplicate data.I am explaining my code below.
session_start();
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$colg_id=1;
$dept_id = $_SESSION["admin_dept_id"];
$user_id=$_SESSION["admin_id"];
$connect = mysqli_connect("localhost", "root", "******", "go_fasto");
$result = mysqli_query($connect, "select plan_id,unit_name from db_unit_plan where dept_id='".$dept_id."' and user_id = '".$user_id."' ");
while ($row =mysqli_fetch_assoc($result)) {
$data[] = $row;
}
print json_encode($data);
Here i need if any unit_name column has same type data then how to skip those rows.Please help me.
Change like this with DISTINCT
$result = mysqli_query($connect, "select DISTINCT unit_name,plan_id from db_unit_plan where dept_id='".$dept_id."' and user_id = '".$user_id."' ");
you have to specify the 'DISTINCT' keyword to get unique results from SQL.
so just try changing your select statement to $result = mysqli_query($connect, "select DISTINCT plan_id .. ");
good luck.
need to get row content from a mysql select statement. Currently starting at high id and desc. Need to take the highest id and get it, and the next 15 in line, and need to store them as variables. Here is an example:
$servername = "localhost";
$username = "_p";
$password = "1";
$dbname = "w";
mysql_connect("localhost", "p", "s") or die(mysql_error());
mysql_select_db("p") or die(mysql_error());
$highest_id = mysql_result(mysql_query("SELECT MAX(id) FROM NE2"), 0);
$result = mysql_query("SELECT content, id FROM NE2 order by ID desc LIMIT 15 ");
while($row[0] = mysql_fetch_array($result)){
echo $row[0]['content'];
You could do it with one query and access the top 16 ids, (the max id and the 15 next ids)
$servername = "localhost";
$username = "_p";
$password = "1s";
$dbname = "wc";
mysql_connect($servername, $username, $dbname) or die(mysql_error());
mysql_select_db("we_ppp") or die(mysql_error());
// Let's get the 16 first highest id's and their content
// Why 16 ? We want the highest and the 15 next
$result = mysql_query("SELECT content, id FROM SEARCH2 order by ID desc LIMIT 0, 16");
// Now it's easied to handle if we just stack the result in a big array
$data_array = array();
while($row = mysql_fetch_array($result)) {
$data_array[] = $row;
}
// Now we have $data_array[0] to $data_array[15] (the 16th row) each one containing
// an associative array resulting from the mysql_fetch_assoc().
// Now if I want the highest id :
$highest_id = $data_array[0]['id'];
$highest_content = $data_array[0]['content'];
// And the next 15 are
for($i = 1; $i < 16; $i++) { // We start at the second line until the 16th (numer 15)
echo $highest[$i]['id'];
echo $highest[$i]['content'];
}
// Now you do whatever you want with $highest and the next ones
The code will be more readable here :
http://pastebin.com/jGF94WJ2
use it like this
$result = mysql_query("SELECT content, id FROM S_ENGINE2 order by ID desc LIMIT 15");
if (mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo $row['content']."<br>";
}
}
may this will help you
The while loop executes row by row, and at an instance you could have only one row (just like array index), so do like
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["id"];
echo $row["contetnt"]);
}
NOTE: mysql_* is deprecated and is not advised . Use PDO for secure database interations
I am having a problem with mysql. My php code is not working.
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
}
?>
I have tested putting some echo on my codes. Once i put the echo code on the while loop the echo doesnt work. Can anyone help me.
Try this :
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
$current_count = 0;
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
}
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
Check if your SELECT query works by change the code:
mysql_query("SELECT * FROM user_count") or die(mysql_error());
Check if there is data in de table user_count and edit the query:
while($row = mysql_fetch_assoc($find_counts))
{
print_r($row); //to print the database row
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts=".$new_count); // no need to specify the database, you already did with mysql_select_db.
}
Dont need to specify DB, and quotes are wrong, change to:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count");
You also might want to specify a page:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count WHERE page = '$this_page'");
what are you trying here ?
mysql_query("UPDATE 'visitor_counter' . 'user_count' SET 'counts'=$new_count");
whats the table name ?
i guess your tablename is user_count
or do you have more than one tablename you like to update ?!?!?
if tablenam eis user_count it should look like
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
so the total while would be
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
}
Important
Dont use
'tablename'
in your sql query... if you like to declair a tablename use
`tablename`
Use single query:
UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1;
then do your SELECT ... FROM
because passing variable into sql query for this kind of operations are not always safe
and here is Your code:
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
mysql_query("UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1");
$counts = array();
$result = mysql_query("SELECT * FROM user_count");
while($data = mysql_fetch_assoc($result)) {
$counts[$data['id']] = $data['counts'];
}
?>
I'm really surprised to see everybody here posts code using the old and deprecated mysql functions (although some of them stated this is wrong). I would like to advice you AGAINST using mysql functions - they are deprecated as of version 5.5. You should use either mysqli or PDO instead. In my opinion, you should be using PDO as it provides support for almost all databases and you could use prepared statements.
Now to your code - I'm not quite sure why would use a cycle to count all of the records in the counts column. A much better way to do this is by using atomic increment - it will also guarantee your counter is properly incremented in case two queries are trying to increment the value simultaneously. Although you haven't posted your table structure, I believe something like this should do the work:
<?php
// Database connection settings
$db_host = '127.0.0.1';
$db_name = 'visitor_counter';
$db_user = 'root';
$db_pass = 'root';
// Try to connect to the database
try {
$dsn = 'mysql:host='.$db_host.';dbname='.$db_name;
$db = new PDO($dsn, $db_user, $db_pass);
} catch ( PDOException $e ){
// Do something if connection could not be established
throw new ErrorException("Could not connect to database!",0,1,__FILE__,__LINE__,$e);
}
// Find counts
// Assuming you have a user_id column in your `user_count` table.
$user_id = 1;
// Update counter
$update = $db->prepare('UPDATE user_count SET counter=(counter+1) WHERE user_id = :user_id');
$update->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$update->execute();
?>
P.S. In this code I'm assuming you're saving the visitor counter in the user_count.counter column and whenever somebody visits that user, the counter column is incremented for that specific user, rather than updating the counter for all users (as your code suggests).
<?php
session_start();
$username = "root";
$password = "password";
$database = "meipolytechnic";
mysql_connect('localhost', $username,$password);
#mysql_select_db($database) or die(mysql_error());
$username=$_SESSION['MM_Username'];
$query = "SELECT rollno FROM users where username = '".$username."'";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result);
mysql_close();
$rows = array();
while($r = mysql_fetch_row($result))
{
$rows[] = $r[0];
}
echo ($rows['rollno']);
?>
i want to retrieve only the logged in users roll no from users table in database
when i run this code
and log in as foo
i get the following stuff
Unknown column 'foo' in 'where clause'
There should be session_start() at the top of the page
query need to change as
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."' ";
EDIT
Please try something before posting a question here. Please google or go through www.w3school.com for clearing this kind of issues. Make a good knowledge about arrays and mysql connection. And mysql_query function won't work latest PHP version.
Please try following code.
$result = mysql_query($query) or die(mysql_error());
$rows = array();
while($r = mysql_fetch_row($result))
{
$rows[] = $r[0];
}
print_r($rows);
To use an array inside a string you need to put a curly bracket before it and after it
so
$query = "SELECT rollno FROM users where username = {$_SESSION['MM_Username']}";
or
$query = "SELECT rollno FROM users where username = ".$_SESSION['MM_Username'];
First of all start session using start_session()
then change your query:
$query = "SELECT rollno FROM users where username = ".$_SESSION['MM_Username'];
then change:
$num = mysql_num_rows($result); instead of $num = mysql_numrows($result);
Try this query
$query = "SELECT rollno FROM users where username = ".$_SESSION[MM_Username]." ";
And start session on same page.
You can use
$username=$_SESSION[MM_Username];
$query = "SELECT rollno FROM users where username = '".$username."'";
and start the session by using session_start()
and you have used two closing tags omit one make it like below
echo ($rows['rollno']);
?>
This type of error occur when query goes false
May be becouse You have not start session, becouse if you dont have session_start(), then nothing will come in session variable... just try as
$query = "SELECT rollno FROM users where username = '".$_SESSION[MM_Username]."'";
may this help you
You must need to use session_start() before using $_SESSION variable in code.
So put below code at start,
session_start();
Then do some modification in query like,
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."'";
first start your session
session_start();
and Change your query like this...
$query = "SELECT rollno FROM users where username = '".$_SESSION['MM_Username']."'";
I am trying to get hold of 1 record from a MySQL table using PHP. I have tried many different SELECT statements, while they all work in MYSQL they refuse to return any result in php.
The countriesRanking table is a simple two column table
country clicks
------ ------
0 222
66 34
175 1000
45 650
The mysql returns the ranking of the country column (1, 2, 3, etc..) and it returned all results EXCEPT the first ranked country. Eg when country=175, should return 1 but no result returned. Direct query via web browser return blank page, no error message. My PHP code
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country'") or die(mysql_error());
$row = mysql_fetch_assoc($result) or die(mysql_error());
$theranking = $row['rank'];
echo $theranking;
EDIT
I tried the following but get the same blank page
var_dump($row['rank']);
EDIT 2
For a successful query print_r($result) returned something like Resource id #4. While print_r($row) returned Array ( [0] => 4 [rank] => 4 ). But when querying for the top ranking country. eg country=175, it returned a blank page.
Give this a try. It is based on your earlier question. MYSQL returns empty result in PHP
MYSQLI version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysqli_connect($hostname,$user,$password,$database);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 175";
$result = mysqli_query($link,$query);
$arr_result = mysqli_fetch_array($result,MYSQLI_BOTH);
return $arr_result['rank'];
}
mysqli_close($link);
}
echo rank();
?>
MYSQL version:
<?PHP
function rank(){
/* connect to database */
$hostname = 'server';
$user = 'username';
$password = 'password';
$database = 'database';
$link = mysql_connect($hostname,$user,$password);
/* check connection */
if (!$link){
echo ('Unable to connect to the database');
}
else{
$query = "SELECT COUNT(*) rank FROM countryTable a JOIN countryTable b ON a.clicks <= b.clicks WHERE a.country = 66";
mysql_select_db($database);
$result = mysql_query($query);
$arr_result = mysql_fetch_array($result,MYSQL_BOTH);
return $arr_result['rank'];
}
mysql_close($link);
}
echo rank();
?>
Assuming you are not getting an error that means you are successfully connecting to your database. You are just not getting back any values.
Try:
$row = mysql_fetch_row($result);
I would usually think $row = mysql_fetch_assoc($result); would work but if neither of these work it must be something within your mysql_query.
You can debug this as below.
make sure your SQL is correct by running it on PHPMyAdmin and check the result.
make sure you don't have any fatal errors, if you get a blank page there is something wrong. Turn on PHP errors and see.
print_r($result) and see whether it's empty.
if you want first ranking only then add the LIMIT 1 to your query
If you want only one record from database than you have to use limit in query
$result = mysql_query("SELECT FIND_IN_SET(clicks,
(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC)
FROM countriesRanking)) rank FROM countriesRanking
WHERE country = '$country' LIMIT 1") or die(mysql_error());
and after that use while loop
while($row = mysql_fetch_assoc($result)) {
$theranking = $row['rank'];
}
echo $theranking;