WHERE clause in INSERT statement using mysql/php [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
After searching on Google, i came to know that,
I can not use a WHERE clause in my INSERT query..
But i want to insert a value on column "Book_4" where "Student_ID = 1"
How can i do that ??
Is there any alternate to do that ?
Will be Thankful to You !
$Query = "INSERT INTO issued_books (Book_4) VALUES ('$IssuedBookNumber')" ;
EDITED:
More Details
Using insert query, when i insert a value in column "Student_ID" in my table. All columns in the row of Student_ID (except Student_ID) shows 0 in my DB.
I dun know what this 0 means according to DB.
It might be Null or numeric 0.
If it is a numeric 0, then it should be updated using the UPDATE statement.
But whenever i'm trying to update it, it never updates using UPDATE statement. That's why i'm asking !
P.S: All columns have Datatype INT.
Hope you understand what i want to say :)
Here is the complete code.
Suppose: Student_ID is already created having the value 2.
IssuedBookNumber = 51
Using the above values:
Result = A new row is created having all columns 0 except the column "IssuedBookNumber" that is having value = 51.
While i want, the result should be:
On row Student_ID = 2, Book_4 should be 51.
The point is, When i inserted a value on Student_ID, all other columns becomes 0 on the same row. But when any of the column on the same row having any number except the 0 (that was automatically came on all columns when i inserted a value in Student_ID). Update Query will work.. !
$IssuedBookNumber = $_POST['IssuedBookNumber'];
$Student_ID = $_POST['StudentId'];
$FetchingQuery = "SELECT * FROM issued_books WHERE Student_ID='" . $Student_ID . "'";
$RunFetchingQuery = mysql_query($FetchingQuery);
while ( $row = mysql_fetch_array( $RunFetchingQuery ) ) {
$Book_1 = $row[ 'Book_1' ];
$Book_2 = $row[ 'Book_2' ];
$Book_3 = $row[ 'Book_3' ];
$Book_4 = $row[ 'Book_4' ];
$Book_5 = $row[ 'Book_5' ];
}
if(!empty($Book_4))
{
$Update = "UPDATE issued_books SET Book_4='$IssuedBookNumber' WHERE Student_ID= '$Student_ID'";
mysql_query ($Update);
}
else
{
$AddQuery = "INSERT INTO issued_books (Book_4) VALUES ('$IssuedBookNumber')";
mysql_query ($AddQuery);
}

That not an INSERT. That's an UPDATE. INSERT statements insert a new row. UPDATE statements update an existing row.
UPDATE issued_books
SET Book_4 = '$IssuedBookNumber'
WHERE Student_ID = '$Student_ID'
(I'm assuming you've properly escaped $IssuedBookNumber and $Student_ID)

If you can add a unique index on the 2 columns combined (book_4, student_id)
This would be a good query andshould replace most of your code above
INSERT INTO issued_books (book_4, student_id) VALUES('$IssuedBookNumber','$Student_ID')
ON DUPLICATE KEY UPDATE
SET Book_4 = '$IssuedBookNumber';
Note: you while loop above is not needed since $Book_4 will always return the value of the last row.
your code will then look like this :)
$IssuedBookNumber = $_POST['IssuedBookNumber'];
$Student_ID = $_POST['StudentId'];
$Update = "UPDATE issued_books SET Book_4='$IssuedBookNumber' WHERE Student_ID= '$Student_ID'";
mysql_query ($Update);
Things you should consider,
Switch to using PDO or mysqli
Escape your variables are your code is vulnerable to a SQL injection. Perhaps after you switch to PDO or mysqli you can use prepare statement.

Why not something like this:
$Query = "INSERT INTO issued_books (Book_4, Student_ID)
VALUES ('$IssuedBookNumber', '$Student_ID')"

Use update statement.
update issued_books set Book_4 = $IssuedBookNumber
where Student_ID = '$Student_ID'

Related

mysql using lastInsertID in the same mysql insert?

I am inserting a single row into a table, one of the columns though needs the lastInsertID to append another column. We are building file names off of record IDs. Instead of doing a 2nd update to the newly inserted record, is it possible to get the value of the ID column and append to it in the same mysql insert?
Using PHP, currently I am doing:
$query = "INSERT INTO table (id,idName) values (null,?)" ;
list($lastID,$inError,$inResult) = dbInsert($query,array("")) ;
Then:
$appString = $lastID . "-S1001.pdf" ;
$query = "UPDATE table SET idName=? WHERE id=?" ;
list($upCount,$upError) = dbUpdate($query,array($appString,$lastID)) ;
But is there a way to merge the INSERT and UPDATE into a single statment?
$apString = "-S1001.pdf" ;
$query = "INSERT INTO table (id,idName) values (null,id.$appString)" ;
list($lastID,$inError,$inResult) = dbInsert($query,array()) ;
Why not create a trigger that will do your update whenever you insert a row into the table?
This way, you don't need to manually do the second query. Just the insert.

Update value of Mysql table inside if else Statement

I run $search query which returns no. of rows and using if Else statement
If (no. of rows>0{
Update The row where symbol=123;
}else{
Insert new row
}
I am able to run the query successfully. I have a column with value (id(primary), name and symbol). I would like to update row value if symbol=123; and insert if it is different then 123.
I am able to insert new row when I enter different symbol but unable to update value although executes successfully if symbol no is same.
Here is my code
$sql="SELECT * FROM entrance WHERE symbol='15369-2017-02'";
$STH = $db->prepare($sql);
$STH->execute(array(symbol));
$User = $STH->fetch();
if (!empty($User)){
$sql = "UPDATE entrance SET name ='Sagar Rawal'
WHERE symbol='15369-2017-02'";
$q = $db->prepare($sql);
$q->execute($sql);
}
else{
$sql = "INSERT INTO entrance(name,symbol) VALUES (:a,:b)";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':b'=>$b));
}
But when I run from Mysql command panel below code
UPDATE entrance SET name="Ritish Karki" WHERE symbol="15369-2017-02"
Then value change successfully.
Any help?
You could use something like this query INSERT ... ON DUPLICATE KEY UPDATE Syntax
INSERT INTO entrance(name,symbol) VALUES ($a,$b) ON DUPLICATE KEY UPDATE name = 'Sagar Rawal';
Why your current approach doesn't work? See Nick's comment below your question

MYSQL INSERT foreach in table [duplicate]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
After searching on Google, i came to know that,
I can not use a WHERE clause in my INSERT query..
But i want to insert a value on column "Book_4" where "Student_ID = 1"
How can i do that ??
Is there any alternate to do that ?
Will be Thankful to You !
$Query = "INSERT INTO issued_books (Book_4) VALUES ('$IssuedBookNumber')" ;
EDITED:
More Details
Using insert query, when i insert a value in column "Student_ID" in my table. All columns in the row of Student_ID (except Student_ID) shows 0 in my DB.
I dun know what this 0 means according to DB.
It might be Null or numeric 0.
If it is a numeric 0, then it should be updated using the UPDATE statement.
But whenever i'm trying to update it, it never updates using UPDATE statement. That's why i'm asking !
P.S: All columns have Datatype INT.
Hope you understand what i want to say :)
Here is the complete code.
Suppose: Student_ID is already created having the value 2.
IssuedBookNumber = 51
Using the above values:
Result = A new row is created having all columns 0 except the column "IssuedBookNumber" that is having value = 51.
While i want, the result should be:
On row Student_ID = 2, Book_4 should be 51.
The point is, When i inserted a value on Student_ID, all other columns becomes 0 on the same row. But when any of the column on the same row having any number except the 0 (that was automatically came on all columns when i inserted a value in Student_ID). Update Query will work.. !
$IssuedBookNumber = $_POST['IssuedBookNumber'];
$Student_ID = $_POST['StudentId'];
$FetchingQuery = "SELECT * FROM issued_books WHERE Student_ID='" . $Student_ID . "'";
$RunFetchingQuery = mysql_query($FetchingQuery);
while ( $row = mysql_fetch_array( $RunFetchingQuery ) ) {
$Book_1 = $row[ 'Book_1' ];
$Book_2 = $row[ 'Book_2' ];
$Book_3 = $row[ 'Book_3' ];
$Book_4 = $row[ 'Book_4' ];
$Book_5 = $row[ 'Book_5' ];
}
if(!empty($Book_4))
{
$Update = "UPDATE issued_books SET Book_4='$IssuedBookNumber' WHERE Student_ID= '$Student_ID'";
mysql_query ($Update);
}
else
{
$AddQuery = "INSERT INTO issued_books (Book_4) VALUES ('$IssuedBookNumber')";
mysql_query ($AddQuery);
}
That not an INSERT. That's an UPDATE. INSERT statements insert a new row. UPDATE statements update an existing row.
UPDATE issued_books
SET Book_4 = '$IssuedBookNumber'
WHERE Student_ID = '$Student_ID'
(I'm assuming you've properly escaped $IssuedBookNumber and $Student_ID)
If you can add a unique index on the 2 columns combined (book_4, student_id)
This would be a good query andshould replace most of your code above
INSERT INTO issued_books (book_4, student_id) VALUES('$IssuedBookNumber','$Student_ID')
ON DUPLICATE KEY UPDATE
SET Book_4 = '$IssuedBookNumber';
Note: you while loop above is not needed since $Book_4 will always return the value of the last row.
your code will then look like this :)
$IssuedBookNumber = $_POST['IssuedBookNumber'];
$Student_ID = $_POST['StudentId'];
$Update = "UPDATE issued_books SET Book_4='$IssuedBookNumber' WHERE Student_ID= '$Student_ID'";
mysql_query ($Update);
Things you should consider,
Switch to using PDO or mysqli
Escape your variables are your code is vulnerable to a SQL injection. Perhaps after you switch to PDO or mysqli you can use prepare statement.
Why not something like this:
$Query = "INSERT INTO issued_books (Book_4, Student_ID)
VALUES ('$IssuedBookNumber', '$Student_ID')"
Use update statement.
update issued_books set Book_4 = $IssuedBookNumber
where Student_ID = '$Student_ID'

update user column with session [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have delete option on my php page but I have added option to archive the data before delete but the same time I want update the user name with the person session user name.
$id=$_GET['id'];
$sql="INSERT INTO c_archive_table(tech, eng, dr) SELECT tech, eng, dr FROM `Com` WHERE `id`='$id'";
$sql_user = "INSERT INTO c_archive_table('','user','$_SESSION['username']') WHERE `id`='$id'";
$sql_delete="DELETE FROM `Com` WHERE `id`='$id'";
so moving to archive and delete working but adding user Session to user column didn't work.
It wont be an INSERT it will be an UPDATE
$sql_user = "UPDATE c_archive_table SET 'user'='".$_SESSION['username']."' WHERE `id`='$id'";
Replace user column with whatever column name the $_SESSION name goes into
$sql = new mysqli(MYSQL_HOST, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASE);
// 1. Find the row in the existing table and get the contents
$query1 = '
SELECT
`tech`,
`eng`,
`dr`
FROM `Cnom`
WHERE
`id` = "'.$sql->real_escape_string($_GET['id']).'"
;';
// Use real_escape_string to sanitize anything that the user could modify
$result1 = $sql->query($query1) or die ("<pre>Query failed:\n$query1</pre>");
// die()ing with the query is always helpful for debugging
$row1 = $result1->fetch_assoc() or die ("<pre>No result returned for id {$_GET['id']}</pre>");
// 2. Insert the contents into the archive
$query2 = '
INSERT INTO `c_archive_table` (
`user`,
`tech`,
`eng`,
`dr`
)
VALUES (
"'.$sql->real_escape_string($_SESSION['username']).'",
"'.$sql->real_escape_string($row1['tech']).'",
"'.$sql->real_escape_string($row1['eng']).'",
"'.$sql->real_escape_string($row1['dr']).'"
);';
$sql->query($query2) or die ("<pre>Query failed:\n$query2</pre>");
// 3. Delete from the original table
$query3 = '
DELETE FROM `Cnom`
WHERE
`id` = "'.$sql->real_escape_string($_GET['id']).'"
;';
$sql->query($query3) or die ("<pre>Query failed:\n$query3</pre>");
That might be a good start, based on what I guess your database tables look like.
By the way, I'd recommend that, when diagnosing MySQL issues, that you do like in this example: write your queries in multiple lines with indents; and use the die (string) construct of PHP to print an error-producing query. You can then have a clear view of the query to see any obvious syntax errors, and MySQL can also tell you what line the error occurred on. You can also copy and paste the die()d query into phpMyAdmin.
More importantly, this is probably not the right setup. What you should have, rather than two redundant tables that carry almost the same information, is one table with a column archived. Then you just change archived to a boolean value (true) and check that whenever you're trying to access it.
For example (pseudocode):
if (accessing_all_records) {
// Access all records that aren't archived
$query = '
SELECT
*
FROM `Cnom`
WHERE
`archived` = 0
;';
}
if (inserting_new_record) {
// Create a new record and set archived to 0 by default (better yet, give it a default value)
$query = '
INSERT INTO `Cnom` (
`field_1`,
...,
`archived`
)
VALUES (
value_1,
...,
0
);';
}
if (archiving) {
// Update the record and set the archived value to 1
$query = '
UPDATE `Cnom`
SET
`archived` = 1
WHERE
`id` = id
;';
}

PHP - Select & Update statement to return and update a multi dimensional array

I have a database that looks like the following
In my database both id & fb_user_id are unique. Id is an auto incremented number.
First i would like to insert a new row for arguments say with the following
$new_first_name = "John";
$new_last_name = "Nolan";
$new_email = "John#Nolan.com";
$new_link_url = "Johns_Link";
$new_signups = 0;
$new_order = $num_rows;
$referred_by = 2;
$new_fb_user_id = 4;
I use this insert statement
$New_Member = mysql_query("INSERT INTO `rotator`.`rotator` (`id`, `fb_user_id`, `first_name`, `last_name`, `email`, `link_url`, `referred_by`, `signups`, `order`) VALUES (NULL, '$new_fb_user_id', '$new_first_name', '$new_last_name', '$new_email', '$new_link_url', '$referred_by', '$new_signups', '$new_order');");
And because the person was referred by fb_user_id number 2 i want to update signups as follows
$update_sponsor_order = mysql_query("UPDATE `rotator`.`signups` = `rotator`.`signups` + 1 WHERE `rotator`.`fb_user_id` = $referred_by;");
This is where i am stuck. Maybe there is a better way to do it than inserting and updating the table as abovee.
What i would like to do now is something like the following select statement but assigning the returned values to a multi dimensional array. Basically i return columns fb_user_id and order where signups is less than 2
$get_link = mysql_query("SELECT `rotator`.`fb_user_id`, `rotator`.`order` FROM `rotator`.`rotator` WHERE `rotator`.`signups` < 2);
Now with my array i want to rotate everything that is in the column order and update the database of what entry is next in line....
Check the following question and replys to see what i am trying to do
Original Question
You're new best friend the pdo class. I know this doesn't exactly answer your question, but if you start using it now, you will thank me later.
Overview here http://www.php.net/manual/en/class.pdostatement.php
And to retreive results: http://php.net/manual/en/pdostatement.fetch.php

Categories