i'm new in php and mysql
i have a problem
i have 2 tables
<?php
$insert = mysql_query("INSERT INTO request (date, type_request, subject, customer)
VALUES (NOW(), '".$type."', '".$subject."', '".$username."')");
$fk = mysql_query("insert into feedback (id_request) select id_request from request where id_request = last_insert_id ");
?>
i've been doing that but still cannot fill the id_request in table feedback
the structure of table is like this
Table Request
id_request auto_increment not_null,-->PK
date,
type_request,
subject,
customer
Table Feedback
id_feedback auto_increment not_null,
id_request,---FK
feedback_user
can anyone give suggest how to update the foreign key
Regards
In your code
$fk = mysql_query("insert into feedback (id_request) select id_request from request where id_request = last_insert_id ");
replace last_insert_id with LAST_INSERT_ID()
since its a MySQL function and not a field.
I know I will get flamed for this, but this is how I would do it:
<?php
$date = date('Y-m-d H:i:s');
$req_query = 'INSERT INTO request (date, type_request, subject, customer) '.
"VALUES ('$date', '$type', '$subject', '$username')";
$req_result = mysql_query($req_query);
$fk_query = 'SELECT MAX(id) id FROM request '.
"WHERE date = '$date' AND type_request = '$type' ".
"AND subject = '$subject' AND customer = '$username'";
$fk_result = mysql_query($fk_query);
$fk_row = mysql_fetch_assoc($fk_result);
$fk = $fk_row['id'];
$fb_result = mysql_query("INSERT INTO feedback (id_request) VALUES($fk)");
?>
Related
I am looking to add a function that will get the largest number from a specific column in a table and add to it before doing an INSERT query. (I cant have it be auto increment as several entries need to have the same value this is controlled through an if statement) however it isnt doing this and isn't increasing it by 1 based off the highest value.
$max = "SELECT MAX(LocationID) FROM boss";
$result = mysqli_query($connection, $max);
$locID = $result+1;
$query = "INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty) VALUES ('0', '$boss', '$type', '$loc', '$locID', '$diff')";
You don't need to use two queries for this, you can do it in the INSERT query.
$query = "INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty)
SELECT '0', '$boss', '$type', '$loc', MAX(locationID)+1, '$diff'
FROM boss";
You forgot to fetch the result
$max = "SELECT MAX(LocationID) as m FROM boss";
$result = mysqli_query($connection, $max);
$result = mysqli_fetch_array($result);
$locID = $result[0]+1;
I'm trying to make my script update the view count by +1 everytime a IP is new.
and after 604800 seconds, if the same user(same IP) comeback again after 604800 seconds view count by+1.
Can someone help me out here.
//Get video id
$id = $_GET['id'];
//Get video title
$videoName = $_GET['idtitle'];
//Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=videodb', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Get user IP
$ip = $_SERVER["REMOTE_ADDR"];
//Insert that user IP, Name, Title and increase view count by +1
//This is what i want to accomplish but is not working!
$insert = $pdo->query("INSERT INTO `videodb`.`videos` ( `ip`, `name`, `title`, `views`) VALUES ('$ip', '$id', '$videoName', `views`+1)");
// Sample Two
//Select the IP from videos
$select = $pdo->prepare("SELECT `ip` FROM `videos`");
$sql = $select->execute();
while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
//If the IP in database is not equal to the user IP in database views +1
if($row->fetch('ip') == $ip){
$pdo->query("UPDATE videos SET `views` = `views`+1 WHERE id = '$id' ");
}}
Add one more column in your table as last_viewed_at DATETIME.
Now before inserting the record into the database:
As you are checking the the record for the last 7 days then query as like below:
$row = "SELECT * FROM videos WHERE
id = 'users.ip.to.check'";
Conditions: You have got record against the users.ip.to.check
now check whether the time difference is more than 7 days.
means.
if (count($row) > 0) {
$ipLastViewAt = new \DateTime($row['last_viewed_at']);
$currentDate = new \DateTime();
$diff = $currentDate->diff($ipLastViewAt)->format("%a");
if ($diff >= 7 ) {
// update the record with the view + 1 and with last_view_at = currentDateTime;
}
} else {
// Insert the record with the view +1 and with last_view_at = currentDateTime;
}
If Ip is unique field then this query should help
INSERT INTO `videodb`.`videos`( `ip`, `name`, `title`, `views`) VALUES ('$ip', '$id', '$videoName', 1) ON DUPLICATE KEY UPDATE `views`=views+1;
is not a full code,just for your information!
Tips:two tables maybe better,one save video info,another save visitor info
videos:id,ip,name,title,views,update_time
// first, select $video info and get the result --- "select * from videos where ip='{$ip}' and id='{$id}'";
// we got $video look like : array('id'=>1,'update_time'=>'1453970786')
$time = time();
if( isset($video['id']) && (($time - $video['update_time']) >= 604800) ){
$pdo->query("UPDATE `videodb`.`videos` SET `views`=`views`+1 AND update_time='$time' WHERE id = '$id'");
}elseif( !isset($video['id']) ){
$pdo->query("INSERT INTO `videodb`.`videos`( `ip`, `name`, `title`, `views`) VALUES ('$ip', '$id', '$videoName', 1)");
}
edit
$pdo->query("INSERT INTO `videodb`.`videos`(`id`, `ip`, `name`, `title`, `views`) VALUES ('$id','$ip', '$id', '$videoName', 1)");
I'm trying to grab SID from the insert into the first table (stories) so I can insert that SID into the writing table in my second insert.
I think the way to do this is with mysql_insert_id(); after the first query, but the primary key that auto-increments is called SID. If mysql_insert_id() could grab that value I'd be all set.
What I am finding from a var_dump is that the $SID = mysql_insert_id(); is just returning the value "0" and I'm not sure why.
There is a column called ID in stores, but if it was grabbing that, the value would be "1". Either way, I wish this method could be written as mysql_insert_SID();
Any idea what I am doing wrong or how I can fix this? And yes, I know this is a deprecated approach, but first I want to figure out how before I worry about converting to PDO.
// Get values from form
$category = $_POST['category'];
$genre = $_POST['genre'];
$story_name = $_POST['story_name'];
$text = $_POST['text'];
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query);
$SID = mysql_insert_id();
$SID2 = "select stories.SID from stories where stories.SID=$SID";
$query2 = "INSERT INTO writing (ID, SID, text, position, approved)
VALUES('$user_ID', '$SID2', '$text', '1','N')";
$result = mysql_query($query2);
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
(http://php.net/manual/en/function.mysql-insert-id.php)
But you aren't executing any query (via mysql_query()). You're just assigning your query to a variable. Try following:
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
mysql_query($query);
$SID = mysql_insert_id();
I think you've forgotten to execute the query most probably?
Try
$SID = mysql_insert_id();
after executing the query
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query); // executing
$SID = mysql_insert_id(); // order of queries is important
If you cannot get the value through mysql_insert_id() then try SELECT LAST_INSERT_ID(). Of course there will be a value if you have executed an insert query with AUTOINCREMENT (which you haven't done yet)
I'm trying to get the last inserted id of multiple inserted rows.
record_id is auto increment
$sql = "INSERT INTO records (record_id, user_id, status, x) values ";
$varray = array();
$rid = $row['record_id'];
$uid = $row['user_name'];
$status = $row['status'];
$x = $row['x'];
$varray[] = "('$rid', '$uid', '$status', '$x')";
$sql .= implode(',', $varray);
mysql_query($sql);
$sql2 = "INSERT INTO status_logs (id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES";
$varray2[] = "(' ', mysql_insert_id(), '$status', '$uid', '$x')";
$sql2 .= implode(',', $varray2);
mysql_query($sql2);
This is the result:
INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', mysql_insert_id(), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active'), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active')
There is no value for mysql_insert_id().
You're mixing php function mysql_insert_id() and SQL INSERT statement syntax.
Either use MySQL function LAST_INSERT_ID() in VALUES clause of INSERT statement
INSERT INTO records (user_id, notes, x) VALUES('1237615', 'this is a note', 'active');
INSERT INTO status_logs (record_id, status_id, date, timestamp, notes, user_id, x)
VALUES(LAST_INSERT_ID(), '1', ...);
^^^^^^^^^^^^^^^^^
or retrieve the last inserted id by making a separate call to mysql_insert_id() right after first mysql_query(). And then use that value when you as a parameter to your second query.
$sql = "INSERT INTO records (user_id, ...)
VALUES(...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
$last_id = mysql_insert_id();
// ^^^^^^^^^^^^^^^^^^
$sql2 = "INSERT INTO status_logs (record_id, ...)
VALUES $last_id, ...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
Note:
You don't need to specify auto_incremented column in column list. Just omit it.
Use at least some sort of error handling in your code
On a side note: Instead of interpolating query strings and leaving it wide open to sql-injections consider to use prepared statements with either mysqli_* or PDO.
Unless I mis-reading your code, you're calling the PHP function mysql_insert_id from within the SQL?
What you need to do is grab that into a PHP variable first, then use the variable in the SQL. Something like this:
// Run the first query
mysql_query($sql);
// Grab the newly created record_id
$recordid= mysql_insert_id();
Then in the second INSERTs just use:
$varray2[] = "(' ', $recordid, '$status', '$uid', '$x')";
I need your help to fix my problem..
first I have 2 tables in mysql dbase.. here are the structures :
doctor1:
--------
no_que autoincrement pk,
doctor_name,
id_patient,
date,
time
status_que:
----------
id_patient,
doctor_name,
no_que fk,
date,
time
I want to insert data into doctor1 and the data will be the same at status_que..
$idp=$_POST['id_patient'];
$dt=$_POST['date'];
$tm=$_POST['time'];
$dn=$_POST['doctor_name'];
$query = "INSERT INTO doctor1 (doctor_name, id_patient, date, time)
values ('$dn', '$idp', '$dt', '$tm')";
$result = #mysql_query($query) or die("REPORT Failed to save data.");
$last_insert_no_que = mysql_insert_id();
#query2 = "INSERT INTO status_queue (id_patient, doctor_name, no_que, date, time)
values ('$idp', '$dn', '$last_insert_no_que', '$dt', '$tm')";
$result = #mysql_query($query2) or die("REPORT Failed to save data.");
but that code doesn't work
it works ! I only have to delete "#" operator.. :) ~ thx you
so here is my code :
$idp=$_POST['id_patient'];
$dt=$_POST['date'];
$tm=$_POST['time'];
$dn=$_POST['doctor_name'];
$query = "INSERT INTO doctor1 (doctor_name, id_patient, date, time)
values ('$dn', '$idp', '$dt', '$tm')";
$result = mysql_query($query) or die(mysql_error());
$last_insert_no_que = mysql_insert_id();
$query2 = "INSERT INTO status_queue (id_patient, doctor_name, no_que, date, time)
values ('$idp', '$dn', '$last_insert_no_que', '$dt', '$tm')";
$result = mysql_query($query2) or die(mysql_error());
>