How to perform insert in one query? - php

Frame: MySQL server on localhost using XAMPP server.
I'm trying to insert all these fields in a particular table "tbl_labelled_images":
id_in_raw_image_table
image
label
gender
Out of them, image comes from another table named as "tbl_raw_image" and id_in_raw_image_table is the id of that image in table "tbl_raw_image".
Then label and gender are the inputs by the user taken on run time using radio buttons. But the problem is I cannot insert all these four attributes in a single query. Query just does not insert anything in the table if all of them are in the same query. I have tried following queries but none of them actually helped:
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
(`label`,`gender`,`image`, `id_in_raw_image_table`) '$label','$gender',
SELECT image, id FROM raw_images.tbl_raw_image
WHERE raw_images.tbl_raw_image.id = $id_raw";
$insert_exec = mysqli_query($conn, $query_insert);
And
$sql = "SELECT * FROM tbl_raw_image WHERE id IN
(SELECT id FROM (SELECT id FROM tbl_raw_image ORDER BY RAND() LIMIT 1) t)";
$sth = $conn1->query($sql);
$result=mysqli_fetch_array($sth);
$id=$result['id'];
$image=$result['image'];
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query2="INSERT INTO tbl_labelled_image(image, label, id_in_raw_image_table) VALUES('$image','$label','$id'); ";
$rs = mysqli_query($conn2, $query2);
But none of them worked for me. As a work around I'm currently using a complex two step insertion as follows:
$sql = "SELECT * FROM tbl_raw_image WHERE id IN
(SELECT id FROM (SELECT id FROM tbl_raw_image ORDER BY RAND() LIMIT 1) t)";
$sth = $conn1->query($sql);
$result=mysqli_fetch_array($sth);
$id=$result['id'];
$image=$result['image'];
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
(`image`, `id_in_raw_image_table`)
SELECT image, id FROM raw_images.tbl_raw_image
WHERE raw_images.tbl_raw_image.id = $id_raw;";
$insert_exec = mysqli_query($conn, $query_insert);
$labelled_id=mysqli_insert_id($conn);
$query_label = "UPDATE labelled_images.tbl_labelled_image SET
`label` = '$label', `gender` = '$gender' WHERE `id`=$labelled_id";
$label_insert_exec = mysqli_query($conn, $query_label);
$query_update_Is_labelled="UPDATE raw_images.tbl_raw_image SET `Is_labelled`= 1 WHERE id= $id_raw; ";
$update=mysqli_query($conn,$query_update_Is_labelled);
It works but it is far from ideal. So my question is that is there any way to perform this insert in one step? Or more generally what should be done when different fields of record to be inserted are from different sources?

You can try to use a static value in your MySQL select query SELECT '$label' as label,'$gender' as gender
complete query:
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
(`label`,`gender`,`image`, `id_in_raw_image_table`)
SELECT '$label' as label,'$gender' as gender, image, id FROM raw_images.tbl_raw_image
WHERE raw_images.tbl_raw_image.id = $id_raw
";
Edited: remove the VALUES() before the SELECT

Related

Insert into if not exist MySQL

I'm using PostgreSQL to get data and i want to insert it into MySQL. I have a php script which allows me to get the data, check for repeated and then insert it into MySQL DB. Problem is that instead of inserting only the non existing data it inserts one random row and doesn't insert nothing else.
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
the variables $episode_col and $episode_values get data from an array called $episode through implode:
$episode_col = implode(", ", array_keys($episode));
$episode_values = implode("', '", array_values($episode));
This is you code.
IF statements are used for comparisons, yours is just fetching the array and there's no condition inside your IF statement. You need to fix the statements to get the columns and their respective values.
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
You can try to use WHERE EXISTS or WHERE NOT EXISTS too.
SELECT DISTINCT column1 FROM table1
WHERE EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
SELECT DISTINCT column1 FROM table1
WHERE NOT EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
For more info: https://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html

Add MySQL Count Column to PHP/HTML Table

I'm developing a website using HTML, PHP and MySQL to access a database. On one page I present a table with data from that database. This is some of the code I'm using:
$sql1 = "SELECT * FROM MyTable ORDER BY ID ASC";
$rs1 = mysqli_query($link,$sql1);
(...)
while($row1 = mysqli_fetch_assoc($rs1)) {
echo "<tr><td>".$row1['ID']."</td><td>".$row1['Field1']."</td><td></td><td>".$row1['Field2']."</td><td>".$row1['Field3']."</td></tr>\n" ;
}
Notice the empty <td></td>? That's because I want to have there the number of time a given ID appears on two other tables (there are foreign keys involved, obviously). I have sorted out the code I need for that:
$sql2 = "SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total";
However, I'm struggling with figuring out a way to add this result to the other table. Any help?
try with this.. it inserts the total to an table after selecting the count.
"INSERT INTO total_table (total)
SELECT (SELECT COUNT(*) FROM MyTable2 WHERE ID2=$row1['ID'])+(SELECT COUNT(*) FROM MyTable3 WHERE ID2=$row1['ID']) AS total
WHERE cid = 2"

Ordering by a value that is not in the database where selecting from

how would i go about ordering by a value that is not in the table where i am selecting from, in this instance the value $count1 is not in the table search.
count has the same identifying id as that of the thing it is being reffered to in the other table, this is where count1 is grabbed
$q = $db->prepare("SELECT COUNT(rating) FROM ratings WHERE id='$id' AND rating = 'd'");
$q->execute();
$count1 = $q->fetchColumn();
$query = "SELECT * FROM search WHERE title LIKE '$each' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
that is from ratings, how would i go about ordering the entries like that, so that they are based off the number of count1 and are decided, i might have to implement something like
$query = "SELECT * FROM search WHERE title LIKE '$each' AND id = '$id' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
Possible Duplicate: Mysql order by specific ID values
Same thing here, you'll just output your $count1as a comma separated string and add it in the SQL query as ORDER BY FIELD(COUNT,___comma_sep_string___)
ratings is a table, not a database. You can join tables or use subqueries to get the desired result, without having to make multiple queries.
You haven't described how the FOREIGN_KEY is set up in the ratings table, but assuming you have something ratings.search_id, this should work:
SELECT search.*, (SELECT COUNT(rating)
FROM ratings
WHERE ratings.search_id = search.id
AND rating = 'd'
) AS rating_count
FROM search
WHERE title LIKE '$each'
ORDER BY rating_count

How to do a MYSQL Select dependant on a previous MYSQL Select

My problem is that I need to SELECT fields from a MYSQL table depending on a previous MYSQL SELECT. Before I did this through an if and else if statement when it could only be one of two things but now I've added a third and so this no longer works. This is the effect I want:
$call = "SELECT * FROM blog_posts WHERE id = $_GET[id] LIMIT 1";
$latest = mysql_query($call);
$result = mysql_fetch_array($latest);
$post_cat = $result['category'];
$sql="SELECT title, post_thumb, id FROM blog_posts WHERE category = $post_cat AND id <> $_GET[id] ORDER BY id DESC LIMIT 6";
Thanks in advance.
$sql="SELECT `title`, `post_thumb`, `id` FROM `blog_posts` WHERE category = '".$post_cat."' AND `id` = '".$_GET[id]."' ORDER BY `id` DESC LIMIT 6";
Put tables/columns in backticks and surround PHP variables in concatenated quotes. At the moment, your query asks MySQL to find a value in the category column which is $post_cat. Not the PHP variable $post_cat, the explicit string $_post_cat.

SQL for sorting out next/previous picture in gallery

I'm working on the photo section of my website, but more precisely on the next/previous link with sorting options.
There are two different option for sorting that exist, first there is a filter (Latest, Trending, Favorite, User etc.) and secondly a sorting option for some of the previous filters (date, views, ratings etc.)
I am having trouble finding a good solution for easily retrieving the next/previous picture for my slideshow.
This is the little bit of SQL I have for getting the next picture for a filter:latest
if ($filter == "latest") {
$sql = "SELECT *
FROM photos
WHERE status = 0 AND id < ".$id."
ORDER BY id DESC
LIMIT 1
";
$result = $db->sql_query($sql);
$sql2 ="SELECT *
FROM photos
WHERE id = (SELECT MAX(id) FROM photos WHERE status = '0')
ORDER BY id DESC
LIMIT 1
";
}
I am wondering if there is an easier way to implement this in my project ? maybe a php class exists to do something like this ?
I feel like I'm going to spend a long time getting all these SQL queries to work properly if I have to do it all like this.
Edit
This is the layout of my photos table
`id` -> unique ID, autoincremented
`title`
`img_name` -> contains the image file name
`date_created` -> when the picture was uploaded
`uploader` -> id of the user that uploaded
`views` -> number of views the picture has
`up_votes` -> votes used to calculate the Wilson score interval
`down_votes`
`net_votes` -> up vote minus down votes
There are other tables like one that links user with friends they have, it is called users_friends
`user_id` -> contains id of the user that added the friend
`friend_user_id` -> contains id of the friend in question
With these two tables I am able to get all the pictures posted by the friend of a user using this sql query :
SELECT *
FROM photos
WHERE uploader IN
(
SELECT friend_user_id
FROM users_friends
WHERE user_id = ':user_id'
)
ORDER BY id DESC
I then have two queries to get the link to the next picture and 2 other queries for the previous one. I have two because one is for when you get at the end of the database to go back to the other end and the other one is for all the other queries. And they look something like this (I'm only posting the next button here)
$sql = "SELECT *
FROM photos
WHERE status = 0 AND id < ".$id." AND Uploader IN (SELECT friend_user_id FROM users_friends WHERE user_id = ".$logedInUser['User_ID'].")
ORDER BY id DESC
LIMIT 1
";
$sql2 ="SELECT *
FROM photos
WHERE id = (SELECT MAX(id) FROM photos WHERE status = '0' AND Uploader IN (SELECT friend_user_id FROM users_friends WHERE user_id = ".$logedInUser['User_ID']."))
ORDER BY id DESC
LIMIT 1
";
$result = $db->sql_query($sql);
if (mysql_num_rows($result)==1) {
$row = $db->sql_fetchrow($result);
return "/photo/".$row["id"]."/".urlFriendly($row["Title"])."/".$filter.$sort;
}
else
{
$result = $db->sql_query($sql2);
$row = $db->sql_fetchrow($result);
return "/photo/".$row["id"]."/".urlFriendly($row["Title"])."/".$filter.sort;
}
I feel like there is a lot of stuff that could be simplified, but I don't yet know how to do it.
I also have the Lower bound of Wilson score sql code to implement for the next/previous button, and it is quite a bit sql code to have to write 4 time. Maybe that I can insert the Wilson score in the photos table, which could simplify a lot the sql code.
It would be helpful if you could post the structure of your table - i.e. what columns/types you have and what each row represents. I'll assume that you have a table where each row represents a photo, and that each photo has an ID, filename, and various other columns that help you filter/sort (such as date, favorite, etc.).
If your filtering and sorting preferences are defined by the user, you can then use those in a single SQL query, whereby you get the full set of ordered results. For instance:
$sort = date;
$filter = favorite;
$sql = "SELECT ID, filename, [other vars here]
FROM photos
WHERE " . $filter . " = TRUE
ORDER BY ". $sort . " DESC";
$result = $db->sql_query($sql);
Now, you can use a function such as mysql_fetch_array to step through each row in your result set and populate some kind of data structure with the current, previous, and next photos.

Categories