How to retrieve and insert ImageId? - php

I have a INSERT function where it inserts the image filename in the 'ImageFile' field in the "Image" table, each row has it's own ImageId thanks to auto number. An example of this is below:
ImageId ImageFile
23 orange.jpg
24 flowers.png
25 castle.png
26 orange.jpg
What I want to do is also insert the ImageId into another table with the QuestionId and SessionId so that this table (Image_Question) can use the ImageId to link the Image table with the Image Question table. But how do I code it so that when I insert image details in the table above, then it will retrieve it's ImageId and also store it in the ImageId in the Image_Question table. Example below:
ImageId SessionId QuestionId
23 AAA 1
24 AAA 2
25 AAA 3
26 AAA 4
I have coded the INSERT values for SessionId and QuestionId but just need help retrieving and inserting the ImageId. Below is the current code:
<?php
session_start();
//connect to db
$i = 0;
$insertimage = array();
for($i = 0; $i < $c; $i++ ){
$insertimage[] = "'". mysql_real_escape_string($_SESSION['id'] ) .
($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '') ."' ,'".
mysql_real_escape_string( $_POST['numQuestion'][$i] ) ."'";
}
$imagesql = "INSERT INTO Question (ImageId, SessionId, QuestionId)
VALUES (" . implode('), (', $insertimage) . ")";
echo($imagesql);
mysql_close();
?>

mysqli_insert_id() after query execute would do the trick

You can get the most recently generated auto_increment id using MySQL's last_insert_id() function. PHP exposes this through mysql_insert_id(). last_insert_id works on a per-connection basis so there is no need to worry about concurrent inserts crossing ids.

Related

Is it possible to make an insert or an update in the same sql query?

I have a question that seems easy but i failed to solve it by miself
i have this table with the statistics of a website visitors
+-----------------------------+
+ date | visits +
+-----------------------------+
+ 2014-03-17 | 198 +
+ 2014-03-18 | 259 +
+ 2014-03-19 | 94 +
+-----------------------------+
My question is what will be the correct way to insert the data to the table.
Currently what i am doing is:
$date = date("Y-m-d");
$result = mysql_query("SELECT Count(*) as count FROM table WHERE date = '$date'");
$row = mysql_fetch_array($result);
$count = $row['count'];
if($count > 0){
mysql_query("UPDATE table SET visits = visits+1 WHERE date = '$date'");
}else{
mysql_query("INSERT INTO table (`date`, `visits`) VALUES ('$date', '1');");
}
Is this the right way to update the table or is there a better one? Is it possible to update it only with one sql query, for example like this:
mysql_query("If row exists update table else insert");
I dont know if this is possible.
Thank you very much in advance! id be very grateful if you can help me on this.
Yes, if your date is the key in the table
INSERT INTO `table`(`date`, `visits`)
VALUES(`$date`, `1`)
ON DUPLICATE KEY UPDATE
`visits`=`visits`+1
Reference: MYSQL:: INSERT ... ON DUPLICATE KEY UPDATE
Note: you are using mysql_* functions those are deprecated (means outdated, no longer supported, no longer modified), so try to use mysqli_* or PDO.
TRY
INSERT INTO `tabelname`(`date`, `visits`) VALUES ($date,1)
ON DUPLICATE KEY UPDATE `visits` = `visits`+1
note: must set date column as UNIQUE index
tip: do not use mysql keyword as column name (date)
Reference

Last insert id value store to same table another specific column

i had following table and columns
Table Name = users
column = user_id, name, email, password, status, identity
i'm using following query for insert data to table users
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['name']);
$password = mysql_real_escape_string($_POST['txtPassword']);
$password = md5($password); //===Encrypt Password
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0')";
$res = mysql_query($query);
header('location:success_register.php');//Redirect To Success Page
}
what i am asking is, i want store last id to column identity also
for example: if last user_id= 10, identity also will be = 10. i mean get last id then store that id to identity column
Result will be look like this
user_id name email password status identity
5 aa aaa#ab.com **** 1 5
6 bbb bbb#ac.com **** 1 6
how to do it,?
In MYSQL, you have alternative possibility to find it, when you think last_insert_id() is not working. You may require to have SELECT privilege on INFORMATION_SCHEMA and its tables.
If you have that privileges, try the following query.
$query = "insert into users( name, email, pasword, status, identity )"
. " values( '$name', '$email', '$password', '1',"
. " ( SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES"
. " WHERE TABLE_NAME='users' and TABLE_SCHEMA=DATABASE() )"
. " )";
And, lastly, suggesting to stop using deprecated API.
Save last insert id like this:
$id = mysql_insert_id();
and use it in next insert
You are looking for:
mysql_insert_id()
mysqli_insert_id(mysqli $link)//for mysqli
PDO::lastInsertId()//for PDO
Other Approach:
if your id column is auto increment and not random then you can select the max id(everytime just after your insert query) from the users table and insert it into whatever column you want.
$id=mysql_result(mysql_query(select max(user_id)
from users),0);
Dont use mysql_ as they are depracated.*
here is what you are looking for. Select max(user_id)+1 and store it in a variable.
Now you need to pass this variable in user_id and identity parameter.
Note that even though user_id is auto increment, it will allow you to insert the new row with specified user_id
i think you can also put it like this
$lastID = MySQLI_insert_id($DBcon); //where Dbcon is your connection to your database
and then
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','$lastID')";
$res = mysql_query($query);
I think you need to insert number of rows in the table after the insert:
It may useful to you
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0',(select COUNT(*)+1 FROM users))";

How to retrieve an id after details are submitted

I am having trouble with a major flaw with my database design. Below is my four tables:
Session Table:
SessionId SessionName
3 EROEW
Question Table:
QuestionId(PK) QuestionNo QuestionContent SessionId (FK)
11 1 Question1 3
12 2 Question2 3
13 3 Question3 3
Image_Question:
ImageQuestionId (PK) ImageId (FK) SessionId (Fk) QuestionNo (FK)
1 1 3 1
2 2 3 2
Image:
ImageId (PK) SessionId (Fk) QuestionNo (FK)
1 3 1
2 3 2
Now as you can see in the Image_Question Table, the QuestionNo refers to a QuestionNo which is non-unique or in other words a non unique field. Now I head this is bad practice.
Now I know you are going to say why not use QuestionId. Well the problem is that I can't use QuestionId because the images are uploaded to each question before a question is submitted and the only way we can give a question its own QuestionId is after the user has submitted the questions.
So what I tried to do was determine which question an uploaded image belongs to by getting the QuestionNo from the page as well as the SessionId.
Now as I have heard this is a bad way of doing it, I want to change QuestionNo (FK) in Image_Question to QuestionId (FK). But I am not going to be able to upload files and insert details of the uplaod after questions are submitted to get the QuestionId, to me that can't be done.
So my question is that is there a way we can some how store each uploaded image into a temp table, get the question number and sessionid for each image belongs to and then from there be able to find the QuestionId and store the QuestionId value in the Image_Question Table?
Below is my current php code where it inserts the values after image is uploaded:
Be very greatful if somebody can update code below but any answer will be helpful:
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES (?)";
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name']; //GET THE IMAGE UPLOADED
$insert->execute();
$insert->close();
$lastImageID = $mysqli->insert_id;
$_SESSION['lastImageID'] = $lastImageID;
$_SESSION['ImageFile'] = $_FILES["fileImage"]["name"];
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : ''); GET THE NAME OF THE SESSION
$sessionquery = "SELECT SessionId FROM Session WHERE (SessionName = ?)"; //FIND SESSIONID by finding it's SESSIONNAME
// Bind parameter for statement
$sessionstmt->bind_param("s", $sessid);
// Execute the statement
$sessionstmt->execute();
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$sessionstmt->bind_result($sessionid);
// This populates $sessionid
$sessionstmt->fetch();
$sessionstmt->close();
$imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionNo) //INSERT DETAILS INTO CURRENT IMAGE_QUESTION TABLE
VALUES (?, ?, ?)";
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err imagequestion";
}
$qnum = (int)$_POST['numimage']; //QUESTION NUMBER IMAGE IS UPLOADED IN
$insertimagequestion->bind_param("iii",$lastImageID, $sessionid, $qnum);
$insertimagequestion->execute();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();
Your biggest problem is the fact that your schema isn't normalized. Doing so should help you some.
Here's how I recommend structuring your database:
Session:
SessionId SessionName
3 EROEW
Question:
QuestionId(PK) QuestionContent SessionId (FK)
11 Question1 3
12 Question2 3
13 Question3 3
Image:
ImageId (PK)
1
2
Image_Question:
ImageId (FK) QuestionId (FK) -- (Composite primary key)
1 11
2 12
The insert order for the tables should be:
Session -> Question -
\
-- Image_Question
/
Image -
You'll be dodging potential update issues, and data conflicts otherwise.

Not deleting row in second table

I want to delete a row from the database depending on what the file name of the image is. Lets say I have 2 tables below:
Image Table:
ImageId ImageFile
01 cat.png
02 dog.png
03 dog_2.png
Image_Question Table:
ImageId SessionId QuestionId
01 AAA 4
02 ABD 1
03 RTD 11
Lets say in my application I delete the file image dog_2.png, then I want it to delete the row which states dog_2.png in the Image Table (This is working fine) and be able to delete the row from the Image_Question Table where the row contains the same ImageId associated with the ImageId and ImageFile name from the Image Table (This is not working).
So for the above example the 2 tables should now look like this after deletion:
Image Table:
ImageId ImageFile
01 cat.png
02 dog.png
Image_Question Table:
ImageId SessionId QuestionId
01 AAA 4
02 ABD 1
But it does not delete the row from the Image_Question Table, how can I get this row to delete?
Below is the full code where it deletes the row from the Image Table and it contains most of the code which has been setup but not fully completed on deleting a row from the Image_Question Table:
$image_file_name = $_GET["imagefilename"];
$img = "ImageFiles/$image_file_name";
echo "$image_file_name was Deleted";
unlink("ImageFiles/$image_file_name");
$imagedeletesql = "DELETE FROM Image WHERE ImageFile = ?";
if (!$delete = $mysqli->prepare($imagedeletesql)) {
// Handle errors with prepare operation here
}
//Don't pass data directly to bind_param; store it in a variable
$delete->bind_param("s",$img);
$delete->execute();
if ($delete->errno) {
// Handle query error here
}
$delete->close();
$imagequestiondeletesql = "DELETE FROM Image_Question WHERE ImageId = ?";
if (!$deleteimagequestion = $mysqli->prepare($imagequestiondeletesql)) {
// Handle errors with prepare operation here
}
// Don't pass data directly to bind_param; store it in a variable
$deleteimagequestion->bind_param("s",....);
$deleteimagequestion->execute();
if ($deleteimagequestion->errno) {
// Handle query error here
}
$deleteimagequestion->close();
You can use a JOIN query to delete from multiple tables in a single query. I think this sort of statement will work for you:
$sql = "
DELETE img, img_q
FROM Image AS img
LEFT JOIN Image_Question AS img_q
ON img_q.ImageId = img.ImageId
WHERE img.ImageFile = ?";

php mysql save mysql with for loop

TABLE:
09:00 -- id_timeslot = 1
09.15 -- id_timeslot = 2
09.30 -- id_timeslot = 3
09.45 -- id_timeslot = 4
10.00 -- id_timeslot = 5
PHP MYSQL:
for($i=0; $i<=2; $i++) {
$mysqli->query("INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES ('" . ++$id_timeslot . "', '" . $id_member . "', '" . $b_ref . "', '" . $id_doctor . "', 1)" )
}
I want the data to be saved twice and increment the id_timeslot.
The above code working fine, but when save cliked. it didnt pick up the right id_timeslot?
for example: if user click on id_timeslot:1, soon it save to database the id_timeslot starts from 2 instead of id_timeslot 1?
if user click on id_timeslot:1, soon it save to database the id_timeslot starts from 2 instead of id_timeslot 1?
This is because you're using a pre-increment rather than a post-increment. If $id_timeslot is 1 before entering the loop, the value of ++$id_timeslot is 2, so the first generated query is:
"INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES ('2', '$id_member', '$b_ref', '$id_doctor', 1)"
If the id_timeslot column is supposed to be an ID for the bookslot record, the best approach is to declare it with the AUTO_INCREMENT attribute and don't insert values for that column:
-- run just once in some MySQL client
ALTER TABLE bookslot MODIFY id_timeslot INT UNSIGNED PRIMARY KEY AUTO_INCREMENT;
// in PHP
$stmt = "INSERT INTO bookslot(id_member, b_ref, id_doctor, status)
VALUES ('$id_member', '$b_ref', '$id_doctor', 1)";
When using double quoted strings, you don't need to concatenate variables. Compare the above statement with your own.
If id_timeslot isn't a unique ID, then you can simply switch to post-increment.
$stmt = "INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES (" . $id_timeslot++ . ", '$id_member', '$b_ref', '$id_doctor', 1)";
This may or may not be a correct approach for various other reasons. Without knowing more about the schema, it's impossible to say.
Off Topic
Depending on where the values for $id_member, $b_ref $id_doctor originate, your script could be open to SQL injection. Rather than inserting values directly into the string, use a prepared statement. MySQLi supports them, as does PDO, which is simpler to use. New code should use PDO, and old code should get updated over time.
You have to fetch last id_timeslot from database and then increase it PHP during inserting.

Categories