Transferring data from one table to another using a where clause mysql - php

I would like to copy data from one table to another, but placing it in a specific row. The variable is set, the tables and query are named correctly and the columns set up correctly.
I would like to select the data circled in black
and place it within the section circled below in black
The query I am using if below. When it runs without the WHERE clause it goes on the row below, when the WHERE clause is added it is blank.
$query = "INSERT INTO Results (Q1A) SELECT Q1AY FROM Answers WHERE User = $email";

Try
$query ="UPDATE Results R SET Q1A= (SELECT Q1AY FROM Answers) WHERE R.User=$email"
This only works if there are only one row in Answers, but your code seems to assume as much.

Related

Clarifications about Multi Queries

I'm trying to execute 2 queries, but whenever I follow the guides online about multi queries, its not doing either of the queries.
What I'm trying to do on the first query is to INSERT or ADD whatever the user inputs on $HISTORY on the record that's currently on colHistory; I.E.:
Current data on colHistory:
A
User inputs 'B' on $HISTORY, the syntax should add 'B' on the 'A' that's currently on record, or 'AB'. Then use the second query to UPDATE all the other records or columns on this particular row.
Here's the code (Please note that the '...' means more code that's unnecessary):
$query = INSERT INTO tbInventory SET colHistory='$HISTORY' WHERE colSerno='$SERIALNUM';";
$query .= "UPDATE tbInventory SET
colImage='$IMAGE',
colSerno='$SERIALNUM',
...
...
colHistory=''
WHERE colSerno='$SERIALNUM'";
mysqli_multi_query($con,$query);
Please note where I declared colHistory as '' before I insert the data from the form. I'm not sure if I'm doing it right on this part. Is there anything that I'm missing?
*Edit:
I have already tried executing the queries one by one as:
mysqli_query($con,"INSERT INTO tbInventory SET colHistory='$HISTORY' ");
mysqli_query($con,"UPDATE tbInventory SET
...
...
colHistory=''
WHERE colSerno='$SERIALNUM'";
Yet it doesn't seem to work either, the whole thing gets ignored.
(** I have a script below the code block above where I could print the results already, and it does run)
Well I can tell you why your first query is broken.
INSERT INTO tbInventory SET colHistory='$HISTORY'
This query is using UPDATE syntax but you are telling the query processor to expect INSERT INTO syntax. So the query is unable to execute.
Decide whether you are needing to UPDATE an existing record or INSERT a new one and alter your query to reflect that. (Change INSERT INTO to UPDATE or change "Set colHistory = '$ History'" to "Values ('$ History', 'col2Val', and so on..")
As for your second query, the syntax looks alright from what you have shown but since you didn't post the entire query its hard to say what is happening there. If you can show more of that query I can update this response.
Here's a good SO question on inserts vs updates.
What are differences between INSERT and UPDATE in MySQL?
I ended up dropping the multi-query method and I did got my intended results by somehow cheating:
I assigned the old data or the data that's currently on the colHistory cell, displayed it, but I disabled the textarea. I then created one more hidden textbox in the script with the old data in it and then hid it to the users view.
I then concatenated both textareas with the new one that I've created that the user could modify, emulating the results wanted.

PHP mysqli query returning result "1" on joins

I have been trying to pull out some values from php-mysql, and it's returning a strange result "1". It comprises of an inner join with a where clause, everything works fine, but the result is strangely "1" when I try to echo out the ID, but I am assured that the ID is not 1. When I run the same query on the MySQL CLI, it returns exactly what I need but in the php, it doesn't even say there's an error.
Interestingly, only the ID is returning "1", everything else is returning the correct values. The ID on the CLI is- "V8FBaMJT6bqPbpRutJgkRdc44S3Gz3H8VjW5iu5E4yhBlLA1/D8o+EcGMUY62LZLrxb2SSkaxBoUwaiQXQv+3OsoDTuheYTy4ibPsy91X8JhNGFjOWM2MWQyMWMxMTBmMTU5YjU5NzU2NGM3OTc1YQ==", so there's no chance that it is equal to "1".
$showPosts = "SELECT * FROM box
INNER JOIN interactions
ON box.u_id=interactions.actorid
WHERE interactions.actorid=?
AND interactions.type IN ('1','5')
ORDER BY box.time_created";
if ($stmt = $conn->prepare($showPosts)) {
/* bind parameters for markers */
$b = "V8FBaMJT6bqPbpRutJgkRdc44S3Gz3H8VjW5iu5E4yhBlLA1/D8o+EcGMUY62LZLrxb2SSkaxBoUwaiQXQv+3OsoDTuheYTy4ibPsy91X8JhNGFjOWM2MWQyMWMxMTBmMTU5YjU5NzU2NGM3OTc1YQ==";
$stmt->bind_param("s", $b);
/* execute query */
$stmt->execute();
/* bind result variables */
$metaResults = $stmt->result_metadata();
$fields = $metaResults->fetch_fields();
$statementParams = '';
//build the bind_results statement dynamically so I can get the results in an array
foreach($fields as $field){
if(empty($statementParams)){
$statementParams .= "\$post['".$field->name."']";
} else {
$statementParams .= ", \$post['".$field->name."']";
}
}
$statment = "\$stmt->bind_result($statementParams);";
eval($statment);
while($stmt->fetch()){
echo $post['id'];
echo $post['time_created'];
}
}
Now, in the result- the first is the strange "1" and the second is the timestamp.
Also, if I remove the INNER join part, and do a simple SELECT * FROM box, it returns the ID perfectly. And I have also tried doing a stmt->num_rows, and it returns '0'. Maybe I am missing something obvious.
I am new to using joins in php mysql and it has been a big headache for me for the last 2 hours, any help is appreciated.
Thank you.
The problem is that you use SELECT * FROM ... which returns every column from any table you are using. This is not what you want. Always write the columns you want to read from the query.
In this case you have more than one Id column in your result set, one from the table box, the other one from the table interactions. The value of $post['id'] will contain the value of the interactions table. So, change the SELECT query by writing:
SELECT box.id, box.time_created FROM ...
Also, do not use the eval() function, ever. You might want to switch to PDO which has a more clear API (the PDOStatement::fetch function returns the next row as an array)
After hours of research, I have come to an working example and it works just fine.
Someone else might face the same problems in the future and make mistakes, so I am posting an answer to the problem here:
Problems:
Having same column names in two joined tables
The first problem was the the table interactions had the same column name id as that of the table box. Since I used SELECT * FROM box along an inner join with interactions, it resulted in the return of the results based on the second id which was of interactions rather than box.
Not storing the results before showing record count
Secondly, the problem was the results were not being stored as in http://php.net/manual/en/mysqli-stmt.num-rows.php, which was a silly mistake.
Solutions:
Addressing the column repition
So, firstly I decided to change the column name of the table interactions for id, and I changed it to inter_id to avoid further conflicts. Though not a very smart step, it will avoid such silly mistakes in the future. Then as pointed out by the previous answer, I had to specify the column names of the results I wanted to output rather than using a SELECT *, so I changed it to
SELECT box.id, box.time_created FROM box
INNER JOIN interactions
ON box.u_id=interactions.actorid
WHERE interactions.actorid=?
AND interactions.type IN ('1','5')
ORDER BY box.time_created";
That pretty much solved the first problem.
Counting the number of results
The second one was just about adding the $stmt->store_result(); to the code and it worked flawlessly just before I did a echo $stmt->num_rows; and it showed the results perfectly.
Thank you, again.

Taking ids from two rows of one MySQL table and entering those values in one row of another MySQL table using PHP

I have two tables, named shows and show_connections. I also ask the user to put in TV show names via POST and those values are show1connection and show2connection. query is a separately defined function that essentially takes your input and puts it in SQL.
I have the following code:
$show1_name = $_POST["show1connection"];
$show2_name = $_POST["show2connection"];
$fail = query ("INSERT INTO show_connections (show1_id) SELECT id FROM shows
WHERE name = '$show1name'");
$fail2 = query ("INSERT INTO show_connections (show2_id) SELECT id FROM shows
WHERE name = '$show2name'");
My main problem is that I want to set show1_id and show2_id as the proper ids in one row. Right now, this syntax (which is the closest I've come to solving this problem) does set show1_id as id of show 1 and show2_id as id of show 2, but they end up on two separate rows. How do I make sure they appear in the same row?
try -
INSERT INTO show_connections (show1_id, show2_id)
SELECT s1.id, s2.id
FROM shows s1, shows s2
WHERE s1.name = '$show1name'
AND s2.name = '$show2name'"
side note - make sure to properly sanitize your user data - $show1name/$show2name. Even better would be to update your code to mysqli_ or PDO and use prepared statements.

MySQL - ListMenus/Comboboxes

I am trying to build a dynamic set of comboboxes/listMenus getting data from a MySQL DB. My database has 5 fields, 1st being id and
topic, sub_topic, info and url
I want to make it so that until user selects a valid choice from box1 that the others are disabled. Once user selects from box 1 box 2 will be activated. Once you make a selection from box 2 then the info and url will be shown.
I have followed a tutorial http://www.ssdtutorials.com/tutorials/series/dependable-dropdown.html and so most of this code is not mine apart from the SELECT statements
I am having problems writing the MySQL for update.php as this populates the other boxes (currently I am sticking with the comboboxes until I have it working.)
I would be grateful for some help, due to the amount of code it can be seen here http://pastebin.com/QNbHR9JK
Thanks in advance.
The first thing I see is that in update.php query, you aren't actually using a where clause. When you execute the prepared query, you pass in a value array, but there aren't any placeholders in the prepared query.
I would expect something like:
$sql = "SELECT `topic`,`sub_topic`,`info`,`url`
FROM `links` WHERE sub_topic=?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
One other thing I notice is that in your foreach in update.php, you are using $row['id'] but you aren't selecting that column in your query.
EDIT
I updated the query to use the proper column in where clause, and removed to group by clause based on discussion.

Why does mysql_num_rows return 1 for a SELECT on an empty table?

The code:
$review = mysql_query("SELECT conceptID, MIN(nextReview) FROM userconcepts WHERE userID='$userID'");
$nrows = mysql_num_rows($review);
echo "$nrows<br />\n";
The query works when the table has such entries and returns the correct column values. However, when the table is empty, as I can confirm right now in HeidiSQL, mysql_num_rows still returns 1, but the column values are empty. (The problem still remains if the table has other values for different userIDs).
I expect this query to return the empty set sometimes during normal operations, and I want to take action based on the existence of a result, but I also want to use the result if it exists. Any idea why this code is not working as I expect it to work (I expect it to return 0 if the table is empty)?
First of all, the query has a very simple problem: you're showing the conceptID field, but not grouping by it. If you want to show a field on a SELECT that uses aggregate functions, you should show it; not doing so is an error, and will make many engines not execute your query.
That aside, whenever you have an aggregate function, and you don't group by anything (i.e., don't add a GROUP BY clause), the result is one row. Regardless of the amount of rows in the table.
The reason why is because when a SQL engine executes a query with only aggregation functions, then it returns one row. So:
select count(*)
from table
where 1 = 2
is going to return 1 row with the value 0. This is the way that all SQL engines work.
Your query is a little different:
select conceptID, MIN(nextReview)
FROM userconcepts
WHERE userID='$userID'"
In most SQL dialects, you would get an error of the from "conceptID not in group by clause" or something like that. That is, the query would have a syntax error.
MySQL supports this. It will return the minimum value of nextReview (from the rows that meet the where condition) along with an arbitrary value of conceptID (from those same rows). In this case, there are no rows, so the values will be set to NULL.
Perhaps, you want one row per conceptId. That query would be:
select conceptID, MIN(nextReview)
FROM userconcepts
WHERE userID='$userID'
group by conceptId

Categories