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
;';
}
Related
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'
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am checking the for the user_id (it is held in a session) - this is working. Then I am running a SELECT query for that user for the database table click_count. I am checking to see if that user has any records within it, ie: $page_count. If not, I want my INSERT statement to run to add that user to the database table along with other data.
The part I do not understand is it seems that my UPDATE query is always running. For example no matter which user I login with my query only updates the only user in the database table. IE: Bob is the only user in the click_count table, if I log in with Pete, Bob's record is being updated.
I have tested the value for $page_count and it equals 0, so my INSERT should be running. I have also tried if ($page_count === 0) {
Does anyone see anything I am missing?
$curPage = $_SERVER['PHP_SELF'];
$clicks = 0;
$setup = 0;
$page_total_count = 0;
var_dump($user_id);
$click_sql = "
SELECT *
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
$click_stmt = $con->prepare($click_sql);
$click_stmt->execute(array($user_id, $curPage));
$click_stmt_rows = $click_stmt->fetchAll(PDO::FETCH_ASSOC);
$page_count = $click_stmt->rowCount();
foreach ($click_stmt_rows as $click_stmt_row) {
$setup_status = $click_stmt_row['setup'];
$page_total_count = $click_stmt_row['page_count'];
}
if ($page_count == 0) {
$click_insert_sql = "
INSERT INTO click_count
(user_id, page_url, page_count, setup)
VALUES(?, ?, ?, ?)
ON DUPLICATE KEY UPDATE page_count=page_count+1;
";
$click_insert_stmt = $con->prepare($click_insert_sql);
$click_insert_stmt->execute(array($user_id, $curPage, 1, $setup));
}
else {
$click_update_sql = "
UPDATE click_count
SET page_count=page_count+1
WHERE user_id = ?
AND page_url = ?
";
$click_update_stmt = $con->prepare($click_update_sql);
$click_update_stmt->execute(array($user_id, $curPage));
}
Table
click_count
CREATE TABLE `click_count` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`page_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`page_count` int(11) NOT NULL,
`setup` int(5) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
UNIQUE KEY `page_url` (`page_url`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Since there is only the one user in the table, there is no record "to insert/update", therefore
ON DUPLICATE KEY UPDATE failed you silently.
A regular UPDATE will suffice:
I.e. and as an example:
UPDATE table SET col_x = 0|1 WHERE col_y = ? // (boolean 0-1)
Note:
If ever you wish to increase a column by counting later on, the syntax would be:
UPDATE table SET col_x = col_x + 1 WHERE col_y = ?
In regards to your asking about how you could improve on your code:
#Fred-ii- Thanks. Yes, it is working now how I want, but if there are ways to improve the code I am always willing to try to learn it. I just remembered people in the past saying that I didn't need the update query at all with the duplicate key update. – Paul
You could use named placeholders :name rather than ? since they are easier to keep track of, but this is of course a matter of opinion that I feel is also shared by many and not just myself.
Footnotes/credits:
I would like to also give credit to the following comment:
"If you always fall into update indicates that $page_count is not zero.. Try to echo() it to see maybe.. I would probably first try to add another user into click_count table and then it may become easier to see where it goes wrong.. – johnyTee"
where the OP responded with:
"#Fred-ii- I figured it out. I used johnyTee's advise and tried adding another user to the database manually and it wouldn't let me because of the unique index for the page_url column. I then removed the unique index from it and now it works perfectly. Thanks for the help! – Paul"
from PHP PDO doc http://php.net/manual/en/pdostatement.rowcount.php
PDOStatement::rowCount() returns the number of rows affected by a
DELETE, INSERT, or UPDATE statement.
if you need th number of rows in select you should use somethings like
$sql = "SELECT *
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
It may be '0' (a string). You can use intval to convert it to an integer.
$page_count = intval( $click_stmt->rowCount() );
http://php.net/manual/en/function.intval.php
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
try like this:
$sql = "SELECT count(*)
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
//insert
}else {
//update
}
}
This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 7 years ago.
I am working on a project and I I have a scenario like this:
I have many field in my table :
table_name : transaction_tbl
-id
-name
-description
-ref_number : text(datatype)
In my inserting here is my code:
$sql = "INSERT INTO transaction_tbl (`name`,`description`,`ref_number`) VALUES ('$name','$desccription',$ref_number)";
if ($conn->query($sql) === false){
trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error , E_USER_ERROR);
}else {
echo "Successful ! Data is inserted in database ^__^" ;
}
As the name itself ref_number or reference number, so there will be a time that I will have a lot of reference number,how can I let it insert if it will have multiple values?
Thanks :)
UPDATE :
I want something like this :
name description ref_number
bag to be use 10359435846
05438547656
035848576
Its not a good practice to have multiple values in one cell (and you should never unless there is a serious reason). It violates basic db rules. Just split this to two tables and assign foreign keys to link them up.
Learn db normalization. There are lot of examples. In here you need to take your un-normalized (0NF) table to at least to 1st normalized level (1NF). But its advised to make it normalized at least up to 3rd level
google for db normalization tutorials. As you request below image will give you an idea(field names are not same as in your question).
First insert the values to table1(Member table) and get the insert id in php use $iid = mysqli_insert_id()
Next add the multiple values as seperate rows into the second table(database table) along with the primary key obtained in first step.
Keep in mind this is not a tutorial site. find more info on net.
for what purpose ? why don't you just insert a new row with the same name and description with different ref_number ?
but if you would like that , you can concatenate your new ref_number with the existing ..
first check if it already exist
get its value then concatenate the new ref number ..
or if it doesn't exist , insert a new row ..
$sql = "SELECT `ref_number` FROM `transaction_tbl`
WHERE `name`='$name' AND `description`='$description'";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
$new_ref = $row['ref_number'] . '|' . $ref_number;
$upd = "UPDATE `transaction_tbl` SET `ref_number`='$new_ref'
WHERE `name`='$name' AND `description`='$description'";
}
else
{
$ins = "INSERT INTO transaction_tbl (`name`,`description`,`ref_number`)
VALUES ('$name','$desccription',$ref_number)";
mysql_query($ins);
}
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'
This question already has answers here:
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
(12 answers)
Closed 8 years ago.
I have a query that will update a row in the database, which works fine providing there is a row there to begin with.
How could I say; update if exists insert if doesn't?
require_once('../scripts/includePDO.php');
$who = $_SESSION['who'];
$formText = $_POST['protext'];
$sql = "UPDATE tbl_profiles SET proText = :formText WHERE user_id = :who";
$q = $conn->prepare($sql);
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->bindValue(':formText',$formText,PDO::PARAM_STR);
$q->execute();
header("Location: ../settings/?status=Done");
Assuming user_id is a unique key in the db:
$sql = "INSERT INTO tbl_profiles (user_id, proText) VALUES (:who, :formText) ON DUPLICATE KEY UPDATE proText = :formText";
Your SQL query should be:
INSERT INTO tbl_profiles (user_id,proText) VALUES (:who,:formText)
ON DUPLICATE KEY UPDATE proText=:formText
This is assuming that user_ID is a unique id
1- simple way is use ORM such as Dotrine
2- How ORM handle this :
usually tables has primary key(id) that should not be null .if you have update then you had select that load this data . in you select load id field in you data structure (array or object or something else) . in save method only check current row you want save that it has id (if this record has id then it exist and need to update else you should save).