How to skip duplicate value while fetching from My sql DB - php

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.

Related

Need Some Help Regarding Fetching Data from Mysql using explode function

In the below script I want to fetch data from mysql using a explode function and also a variable within an explode function.
Here's how I want to get
<?php
include ('config.php');
$track = "1,2,3";
$i = 1
$trackcount = explode(",",$track);
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>
This is the code
$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
I want sql to fetch data from tracks table where id = $trackcount[$i]
Whatever the value of $trackcount[$i] mysql should fetch but it shows a blank screen.
If I put this
$sql = "SELECT * FROM tracks WHERE id='$trackcount[1]'";
It works perfectly
save your $trackcount[$i] in one variable and then pass it in the query as given below
<?php
include ('config.php');
$track = "1,2,3";
$i = 1;
$trackcount = explode(",",$track);
$id=$trackcount[$i];
$sql = "SELECT * FROM tracks WHERE id='$id'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>
and one more thing check your previous code with echo of your query and see what is passing ok.
echo $sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//like this
problem is with your query
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//change
to
$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
Generally you would want to use the IN operator with this type of query, so for you this would be:-
$sql="SELECT * FROM `tracks` WHERE `id` in (".$track.");";
or, if the $ids are in an array,
$sql="SELECT * FROM `tracks` WHERE `id` in (".implode( ',', $array ) .");";

Displaying a SQL table data for a specific user

I want to display the table participantes with the columns sorteo, nombre and fecha.
The user info is on another table sellify_users (usern column).
I want to display only that user data using:
SELECT * FROM participantes WHERE nombre = 'usern'
But usern is not in the same table, so if possible I want to call the sellify_users to get the usern data.
<?php
$user = 'database_user';
$password = 'database_pass';
$database="database_name";
mysql_connect(localhost,$user, $password);
#mysql_select_db($database) or die( "Unable to select database");
echo $query = "SELECT * FROM participantes WHERE nombre='usern'";
$result = mysql_query($query);
mysql_close();
?>
If you meant that a user has a record in the table sellify_users and you need to find the usern from it in order to use it in the next query:
$query = "SELECT * FROM participantes WHERE nombre='usern'";
Then all you need to do is to run a query for the table sellify_users first and get the value usern from it, store it in a variable and then use that in your second query. Something like:
$query1 = "SELECT * FROM sellify_users";
$result1 = mysqli_query($con, $query1);
$row1 = mysqli_fetch_assoc($result1);
$usern = $row1['usern'];
$query2 = "SELECT * FROM participantes WHERE nombre='usern'";
$result2 = mysqli_query($con, $query2);
while($row2 = mysqli_fetch_assoc($result2)){
echo $row2['ColumnNameHere1'];
echo $row2['ColumnNameHere2'];
}
Notice: I've passed $con which denotes a connection variable, i.e.
you should read about mysqli or PDO and if there's anything you do not understand, feel free to shoot a query.
EDIT:
If by any chance you are trying to use the last inserted record, you should look for mysqli_insert_id($con); and use that instead.

How to query the max id from mysql?

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.

PHP fetching data from MySQL database

So I'm trying to fetch data in a many-to-many relationship.
So far I have this, which finds the user:
$user = $_SESSION['user'];
$userID = mysql_query("SELECT * FROM users WHERE user='$user'") or die(mysql_error());
And I know that to echo this information I have to put it in an array like so:
while ($r = mysql_fetch_array($userID)) {
echo $r["0"];
}
This works fine, but when I try to find this variable in another table, I'm not sure what to use as the variable:
$projects = mysql_query("SELECT projects_ID FROM projects_users WHERE users_ID='???'") or die(mysql_error());
I've tried replacing ??? with $userID and $r, but to no avail. I know the code works because it's fine when I put a user ID in manually - where have I gone wrong?
$user = $_SESSION['user'];
$query = mysql_query("SELECT * FROM users WHERE user='".mysql_real_escape_string($user)."' LIMIT 1") or die(mysql_error()); //--note the LIMIT
$result = mysql_fetch_array($query);
$userID = $result[0];
$projects = mysql_query("SELECT projects_ID FROM projects_users WHERE users_ID='$userID'") or die(mysql_error());
Untested, but this should work:
$user = mysql_real_escape_string($_SESSION['user']);
$query = mysql_query("SELECT * FROM users WHERE user='$user'") or die(mysql_error());
$result = mysql_fetch_array($query);
$userID = $result[0];
$projects = mysql_query("SELECT projects_ID FROM projects_users
WHERE users_ID='$userID'") or die(mysql_error());
I your case, you'd need to place $r[0] there.
I think this code is helpful for beginners when you want to get data in array form
we use mysqli instead of mysql to protecting your data from SQL injection.
Before use this code check the database connection first
<?php $tableName='abc';
$qry="select * from $tableName";
$results=mysqli_query($qry);
while($records=mysqli_fetch_array($results))
{
$firstrecord=$records[1];
$secondrecord=$records[2];
}
?>
You can get your projects with one query:
$user = mysql_real_escape_string($_SESSION['user']);
$query = mysql_query("SELECT pu.projects_ID FROM users u
INNER JOIN projects_users pu ON (pu.users_ID = u.users_id)
WHERE u.user='$user'") or die(mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['projects_ID'];
}

get multiple values from table1, change them to values based on table2 and write the result to table1

hi
i can rewrite a column's values in a mysql databse based on another columns values, but this time i need to do this with a twist...
there are two tables (and multiple values at once): specifications and products.
products has two columns: specificationids and specificationorderids
specifications has two columns aswell: id and specificationorder
specificationids has multiple values formatted like this: ,31,29,27,18,
these are also the id in the specifications table. each id has a specificationorder value (same row, other column). now what i want to do is, that i want to swap the values of the id with the value of specificationorder and write these to specificationorderids in the products table in the same format.
ofcourse this process has to loop through all the id's in the products table.
i hope i made the problem clear and understandable
thanks for your help!
Swap id and specificationorder, specificationorder writen in specificationorderids if I understand you:
<?php
/* Swap id and specificationorder */
$sql = "SELECT id, specificationorder from specifications";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{
$id = $row[0];
$sporder = $row[1];
$sql = "UPDATE specifications SET id=$id, specificationorder=$sporder WHERE id=$id";
mysql_query($sql);
}
/* specificationorder writen in specificationorderids */
$sql = "SELECT specificationorder from specifications";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{
$sporder = $row[0];
$sql = "INSERT INTO products(specificationorderids) VALUES($sporder)";
mysql_query($sql);
}
?>
for the past couple days i havent been able to come up with a normal code, so heres what ive got so far. ive added comments so you know what i was thinking when experimenting with the code... as in my previous comment i include an image of what i want to achive: img822.imageshack.us/i/specm.png
//get specificationids
$sql = "SELECT specificationids from products";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$spids = $row[0];
//get specifications
$sql2 = "SELECT id from specifications";
$result2 = mysql_query($sql2);
$row2 = mysql_fetch_row($result2);
$spid = $row2[0];
//get specificationorder
$sql3 = "SELECT specificationorder from specifications";
$result3 = mysql_query($sql3);
$row3 = mysql_fetch_row($result3);
$sporder = $row3[0];
//if the value of specificationids matches a specificationid, then....
while(VALUES($spids)==$spid)
{
$spids=$sporder; //...it should be replaced by the specificationorder
//and then update the specificationorderids column accordingly
$sql = "UPDATE products(specificationorderids) VALUES($spids)";
mysql_query($sql);
}

Categories