I have a db with columns like the following:
id options
1 Website,Website,Newspaper,Newspaper,TV,TV,Radio,Radio
2 Website,Website,Newspaper,Newspaper
3 Website,Website,TV,TV
The goal is to remove the duplicate entries and normalize the options column to:
id options
1 Website,Newspaper,TV,Radio
2 Website,Newspaper
3 Website,TV
I have developed the following PHP code:
$sql = "SELECT id, options FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode( ',' , $row['options'] );
if(count($values_array) != count(array_unique($values_array)))
{
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE table SET options=".$new." WHERE id = '$id'";
}
}
} else {
echo "0 results";
}
$conn->close();
This doesn't get the job done. Everything seems to work but the attempt to update the options columns with the new array data.
This doesn't seem too difficult, just looking for a little guidance on how to make it work.
Thanks in advance!
You can do it directly in mysql
UPDATE T
JOIN
(SELECT id,GROUP_CONCAT(DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(t.options, ',', sub0.aNum), ',', -1)) AS ids
FROM t
INNER JOIN
(
SELECT 1 + units.i + tens.i * 10 AS aNum, units.i + tens.i * 10 AS aSubscript
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
) sub0
ON (1 + LENGTH(t.options) - LENGTH(REPLACE(t.options, ',', ''))) >= sub0.aNum
GROUP BY id)x
ON x.id=t.id
SET t.options=x.ids
FIDDLE
Inspired by this answer
Try This:
$sql = "SELECT id, options FROM table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode(',', $row['options']);
if (count($values_array) != count(array_unique($values_array))) {
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE table SET options=" . $new . " WHERE id = '$id'";
/* seems you missed this */
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
/* you declared sql query but not executed it */
}
}
} else {
echo "0 results";
}
$conn->close();
hope it was helpful :)
As stated in other answers, your quotes are wrong and you didn't execute the UPDATE query, there's another thing you need to know.
table is a reserved keyword in MySQL, so you can't use it like that in your query. Use backticks to escape it.
So your code should be like this:
$sql = "SELECT id, options FROM `table`";
$result = $conn->query($sql);
if ($result->num_rows > 0){
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode( ',' , $row['options'] );
if(count($values_array) != count(array_unique($values_array))){
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE `table` SET options='".$new."' WHERE id = '$id'";
$conn->query($sql);
if($conn->affected_rows){
echo "success<br />";
}else{
echo "error<br />";
}
}
}
}else{
echo "0 results";
}
$conn->close();
Here's the reference:
Keywords and Reserved Words
I added the following code to my PHP as showcased by Ajjay Aroraa --
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
The final code for my entire application:
$sql = "SELECT id, options FROM tdata";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$values_array = explode( ',' , $row['options'] );
if(count($values_array) != count(array_unique($values_array)))
{
// find duplicate values in the array
$likes = array_unique($values_array);
$new = implode(',', $likes);
$sql = "UPDATE tdata SET options='".$new."' WHERE id = '$id'";
// execute update query
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
}
} else {
echo "0 results";
}
$conn->close();
Thanks to all who replied -- this is a quick fix as I work to normalize the tables.
Related
Hi i'm quite newbie in php language and i need to find same values in DESCRIPTION column in my database table.
id-------DESCRIPTION
1-------Final
2-------Exam
3-------Test
4-------Test
5-------Mid
6-------Quiz
7-------Quiz
As output it needs to be like:
Final
Exam
Test
Test
Mid
Quiz
Quiz
If a value repating just change them style is enough but i'm really don't know how to do it.
<?php
$check = mysqli_query($connection,"SELECT * FROM EXAMS");
while($test=mysqli_fetch_array($check))
{
echo $test["DESCRIPTION"];
}
?>
Use an EXISTS subquery to look if the same value exists for another id:
$result = $connection->query("
SELECT e.id, e.DESCRIPTION, EXISTS(
SELECT *
FROM EXAMS e2
WHERE e2.DESCRIPTION = e.DESCRIPTION
AND e2.id <> e.id
) as is_duplicate
FROM EXAMS e
ORDER BY e.id
");
Then check in PHP if it is a duplicate (if ($row['is_duplicate'] == 1)) and mark it bold:
while($row = $result->fetch_assoc())
{
if ($row['is_duplicate'] == 1) {
echo "<strong>$row['DESCRIPTION']</strong><br>";
} else {
echo "$row['DESCRIPTION']<br>";
}
}
PHP solution
$result = $connection->query("SELECT * FROM EXAMS");
$data = $result->fetch_all(MYSQLI_ASSOC);
$counts = array_count_values(array_column($data, 'DESCRIPTION'));
foreach($data as $row)
{
if ($counts[$row['DESCRIPTION']] > 1) {
echo "<strong>$row['DESCRIPTION']</strong><br>";
} else {
echo "$row['DESCRIPTION']<br>";
}
}
Hello
i'm trying to make a table with this query but i cant get it to work. the thing is that it cant select 2 query's at a time but i dont know another way for it..
$active_ids = '1, 3, 4';
$query = "SELECT * FROM users WHERE id IN ({$active_ids})";
$result = $mysqli->query($query);
$query = "SELECT dj, count(*) AS n FROM timetable WHERE dj IN ({$active_ids}) GROUP BY dj";
$result = $mysqli->query($query);
while($row = $result->fetch_assoc()){
echo $row['username'], "<br/>";
echo $row['n'], "<br/>";
}
Try this:
$active_ids = '1, 3, 4';
$result = $mysqli->query("
(SELECT * FROM users WHERE id IN ({$active_ids}))
UNION
(SELECT dj, count(*) AS n FROM timetable WHERE dj IN ({$active_ids}) GROUP BY dj)
") ;
if (!$rec = mysqli_fetch_array($result)) {
echo ("Sorry, no records found");
}
else {
do {
echo ($rec["username"]);
echo "<br />";
echo ($rec["n"]);
echo "<br />";
}
while ($rec = mysqli_fetch_array($result));
}
$active_ids = '1, 3, 4';
$query = "SELECT users.* from users
LEFT JOIN timetable ON users.id=timetable.dj
WHERE users.id IN ({$active_ids})
UNION
SELECT timetable.dj,timetable.count(*) as n from timetable
RIGHT JOIN users ON timetable.dj=users.id
WHERE timetable.dj IN ({$active_ids}) GROUP BY timetable.dj
";
$result = $mysqli->query($query);
while($row = $result->fetch_assoc()){
echo $row['username'], "<br/>";
echo $row['n'], "<br/>";
}
I don't know it is certainly true but can you try this code ?
I would like to know what the fastest way is to make the following SQL call using PHP. I am using procedural mySQLi.
$dcount = "SELECT max(id) FROM deposits";
$result = mysqli_query($conn,$dcount);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$count = $row["max(id)"];
echo $count;
echo ",";
}
} else {
echo '0';
}
//second query
$ucount = "SELECT max(int) FROM anothertable";
$result2 = mysqli_query($conn,$ucount);
if (mysqli_num_rows($result2) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$count = $row["max(int)"];
echo $count;
echo ",";
}
} else {
echo '0';
}
Is there a way to make the execution faster than like this, maybe to echo the results from both queries after the first if statement?
It just seems rather long to me.
Thanks in advance.
SELECT max(id) as max_id, (SELECT max(int) as max_int FROM anothertable) as max_int
FROM deposits
Not tested, but something like it should work
$dcount = "
SELECT max(id) as max,'deposit' as table_name FROM deposits
UNION
SELECT max(id) as max,'another' as table_name FROM anothertable
";
$result = mysqli_query($conn,$dcount);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo $row["table_name"].":".$row["max"]."\n";
}
} else {
echo '0';
}
SELECT d.max(id) as d_max_id, a.max(int) as a_max_int FROM deposits as d JOIN anothertable as a ON d.id = a.id;
is what you need for multiple tables
$row['d_max_id']
will give you deposits.max(id) now
You have to edit the d.id = a.id accordingly to what you want the two tables to match on
If you cant join try this:
SELECT max(id) as max_id, (SELECT max(int) FROM anothertable) as max_int FROM deposits;
SELECT max(id) as max_id, max(int) as max_int FROM deposits ,anothertable
Good evening,
I have a problem when i select some data from table. So, first, i call a select that return the last row of the table. After this, i insert new data in that table, and now call that select again and give me the same result of the first select. What i want is, when i insert, the last select returns the data inserted. If i execute another select already give me the last value inserted. My code is written in PHP and i use the interface mysqli.
I already use transactions, refresh, set the cahce of mysqli to 0 in php.ini.
Thanks.
EDITED 2: I make a test:
<?php
include 'conf.php';
$query="INSERT INTO assinante.comentarios (id_cmnt,id_user,comentario,now_data) values (null,4,'coiso',NOW());";
$res= mysqli_query($link,$query);
$query="SELECT * FROM $db_assin.comentarios;";
$res= mysqli_query($link,$query);
$linha = mysqli_fetch_assoc($res);
print_r($linha);
$query="INSERT INTO assinante.comentarios (id_cmnt,id_user,comentario,now_data) values (null,3,'ola',NOW());";
$res= mysqli_query($link,$query);
$query="SELECT * FROM $db_assin.comentarios;";
$res= mysqli_query($link,$query);
$linha = mysqli_fetch_assoc($res);
print_r($linha);
And it return:
Array ( [id_cmnt] => 29 [id_user] => 3 [comentario] => coiso [now_data] => 2014-01-29 02:10:24 ) Array ( [id_cmnt] => 29 [id_user] => 3 [comentario] => coiso [now_data] => 2014-01-29 02:10:24 )
It seems that save in buffer or something like this. If you can help i appreciate.
EDITED: The code
function getComentarios(){
include 'conf.php';
$query =
" SELECT utili.username, cmnt.comentario , cmnt.now_data , cmnt.id_cmnt
FROM ".$db_assin.".comentarios cmnt, ".$db_assin.".utilizadores utili
WHERE utili.id_user = cmnt.id_user
ORDER BY cmnt.id_cmnt DESC
LIMIT 1;";
$resultado = mysqli_query($link,$query);
if($resultado){
$linha = mysqli_fetch_array($resultado);
$json = json_encode($linha);
echo $json;
}
else{
echo mysqli_error($link);
}
mysqli_free_result($resultado);
}
function ins_comment($id_user,$comment){
include 'conf.php';
$data = date('Y-m-d H:i:s');
mysqli_autocommit($link, FALSE);
mysqli_query($link,"BEGIN");
$query_ins = "INSERT INTO ".$db_assin.".comentarios (id_cmnt,id_user,comentario,now_data) "
. "values (null,$id_user,'$comment',NOW());";
if (!$res_ins = mysqli_query($link,$query_ins)){
echo mysqli_error ($link);
mysqli_rollback($link);
}
else{
mysqli_commit($link);
}
mysqli_autocommit($link, TRUE);
mysqli_refresh($link, MYSQLI_REFRESH_HOSTS);
return $res_ins;
}
function comentar(){
include 'conf.php';
$user_c=$_POST['user_c'];
$comment=$_POST['comment'];
$query = "SELECT u.id_user "
. "FROM ".$db_assin.".utilizadores u "
. "WHERE u.username='$user_c';";
if($resultado = mysqli_query($link, $query)){
if (($linha = mysqli_fetch_array($resultado, MYSQLI_ASSOC)) != NULL){
$id_user=$linha['id_user'];
$query = "SELECT c.comentario "
. "FROM ".$db_assin.".utilizadores u, ".$db_assin.".comentarios c "
. "WHERE u.id_user=c.id_user AND u.id_user='$id_user';";
if($resultado = mysqli_query($link, $query)){
if (($linha = mysqli_fetch_array($resultado, MYSQLI_ASSOC)) != NULL){
if(strcmp($linha['comentario'],$comment)!=0){
if($res=ins_comment($id_user, $comment))
echo "Comentário submetido";
}
else{
echo "O mesmo comentário não pode ser submetido duas vezes!";
}
}
else{
if($res=ins_comment($id_user, $comment))
echo "Comentário submetido";
}
}
}
mysqli_free_result($resultado);
}
else echo mysqli_error($link);
}
Your second query doesn't have an order by. Try
SELECT c.comentario
FROM ".$db_assin.".utilizadores u, ".$db_assin.".comentarios c "
WHERE u.id_user=c.id_user AND u.id_user='$id_user'
ORDER BY c.id_cmnt DESC
LIMIT 1;
By the way, you should learn to use explicit join syntax. This query is better written as:
SELECT c.comentario
FROM ".$db_assin.".utilizadores u join
".$db_assin.".comentarios c
on u.id_user = c.id_user
WHERE u.id_user = '$id_user'
ORDER BY c.id_cmnt DESC
LIMIT 1;
I have been going over this for a few days now and keep reaching stumbling blocks. I am trying to select a unique id from table2 and match it against an id in table1. If the id is matched, update the row in table1 and remove the record from table2. If there is no match then insert the record into table1.
I have got to a point where I can update the records and insert the new ones but I cannot seem to delete the matched record before the insert therefore creating a duplicate. I have tried a delete join query after the update but because the new logon_id has a character prepended to it, it no longer matches in table2.
I was doing an update join before for updates but I had too many queries going on so trying to keep it simple.
Any advice? Still a newb at this game.
$table2_query = "SELECT * FROM table2";
$table2_result = mysql_query($table2_query);
$table2_count = mysql_num_rows($table2_result);
if($table2_count == 0) {
if(mysql_error()) {
echo 'Error: '.mysql_error();
}
}
while($table2_row = mysql_fetch_array($table2_result, MYSQL_ASSOC)) {
$check_number_length = strlen($table2_row['unique_id']);
if($check_number_length < 7) {
if(substr($table2_row['unique_id'], 0, 2) < 35) {
$logon_id = 'n' . $table2_row['unique_id'];
}else {
$logon_id = 'v' . $table2_row['unique_id'];
}
}else {
$logon_id = $table2_row['unique_id'];
}
// Set variables for insert query for creation of a new user record
$first_name = $table2_row['firstname'];
$last_name = $table2_row['lastname'];
$email_address = $table2_row['email'];
$duplicates_query = "SELECT * FROM table1 WHERE '$logon_id' = logon_id";
$duplicates_result = mysql_query($duplicates_query);
$duplicates_row = mysql_fetch_array($duplicates_result);
$duplicates_count = mysql_num_rows($duplicates_result);
if($duplicates_count == 0) {
if(mysql_error()) {
echo 'Error: '.mysql_error();
}
}else {
$update_records_query = "UPDATE table1 SET first_name='$first_name', last_name='$last_name', email_address='$email_address'";
$update_records_result = mysql_query($update_records_query);
$update_records_count = mysql_affected_rows();
echo $update_records_count;
}
$create_records_query = "INSERT INTO table1 (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
$create_records_result = mysql_query($create_records_query);
$create_records_count = mysql_affected_rows();
if($create_records_count == 0){
if(mysql_error()){
echo 'Error: '.mysql_error();
}
}
echo $create_records_count . ' record(s) created.';
}
$res = mysql_query ("SELECT count(table1.login_id) AS count FROM table2 LEFT JOIN table1 ON table2.login_id = table1.login_id WHERE table2.login_id = \"".$login_id."\";") or die ("Error joining tables");
/*joins both tables together and selects both id's from tables */
$row = mysql_fetch_assoc($res); // should only return one row so grab first
if ($row['count'] > 0) { // check if id exists in both tables (duplicates)
// updates rows from one table into another
mysql_query('UPDATE table1,table2 SET table1.username = table2.username, table1.password = table2.password, table1.email = table2.email WHERE table1.login_id = "'.$login_id.'" AND table2.login_id = "'.$login_id.'";') or die ("error updating table1");
//delete old row
mysql_query('DELETE FROM table2 WHERE login_id = "'.$login_id.'";') or die("error deleting from table2");
}else { // if id doesn't exist in table1
mysql_query ("INSERT INTO table1(username,password,email) SELECT username,password,email FROM table2 where login_id = '".$login_id."';") or die ("error inserting into table1");
}
remove the n at the beginning of login_id on table1
UPDATE table1 set login_id = replace(login_id,"n","");
new update query if remove n at begin of login_id
mysql_query ('UPDATE table1,table2 SET table1.username = table2.username, table1.password = table2.password, table1.email = table2.email WHERE table1.login_id = table2.login_id AND table1.login_id = "'.$login_id.'";');