I am trying to use $mysqli->insert_id to rename a file so my program can create more than one file. Instead it just creates one file with an id of 0 and each time it overwrites that file instead of creating a new one. I am wondering if I need to increment $mysli->insert_id or something.
But basically I want each file to be named the 'job_id'.fasta. Right now they all are 0.fasta.
I am confused because when I use mysqli->insert_id for my insert statement it correctly assigns job_ids to each new job. So when I SELECT * FROM Job I get a huge list of all the jobs 1-100. I want the files that are created from a job to be called the job_id instead of just 0.
Here is the code that I have.
<?php
if(isset($_POST['submit'])){
// echo "submit1";
//declare variables to what the user defines them as
$db = $_POST['database'];
$evalue = $_POST['evalue'];
$sequence = $_POST['BlastSearch'];
$hits = $_POST['hits'];
//insert the values into the database
//create a new .fasta file and put the sequence the user wants to search for in that file
$file = 'uploads/'.$mysqli->insert_id.'.fasta';
$current = $_POST['BlastSearch'];
file_put_contents($file, $current);
//execute the BLAST Tool
// Do this execute statement if the user inputs his own sequence. (Use new.fasta)
?>
So the insert_id increments for inserting an id into the database for job_id but it doesnt increment in my $file = 'uploads/'.$mysqli->id or my exec function.
I guess you missed the idea somewhere.
It is not clear what is your problem according to your code.
Let me explain why I can't understand your issue.
Here is transformed fragment of your code:
$mysqli->query("INSERT INTO `Job` (`uid`, `input`, `status`, `start_time`, `finish_time`) VALUES ('1', '" . $sequence . "', 'running' , NOW(), NOW())");
$insertedJobId = $mysqli->insert_id;
$mysqli->query("INSERT INTO `BLAST`(`db_name`, `evalue`, `job_id`) VALUES ('" . $db . "','" . $evalue . "', '".$insertedJobId."')") or die(mysqli_error($mysqli));
$insertedBlastId = $mysqli->insert_id;
//execute the BLAST Tool
// Do this execute statement if the user inputs his own sequence. (Use new.fasta)
exec('/students/groups/cs4380sp15grp4/blast/blast-2.2.26/bin/blastall -p blastp -d db -i /students/groups/cs4380sp15grp4/public_html/home/uploads/'.$insertedBlastId.'.fasta -m'.$evalue.' -o outputSEQ -v'.$hits.' -b'.$hits);
So which insert_id id is not incremented? $insertedJobId or $insertedBlastId ?
Related
how can i update and insert together
require_once ('database.php');
$name = mysql_real_escape_string ($_REQUEST["name"]);
$course = mysql_real_escape_string ($_REQUEST["course"]);
$email = mysql_real_escape_string ($_REQUEST["email"]);
$contact = mysql_real_escape_string ($_REQUEST["contact"]);
$Date = mysql_real_escape_string ($_REQUEST["Date"]);
$sql = "SELECT * FROM registerlist WHERE name = '" . $name . "'";
$result = mysql_query ($sql, $dbconn);
if (mysql_num_rows ($result) > 0) {
$resultStr = header("Location:blog.php");
} else {
$result = "SELECT * FROM courselist WHERE cname = '" . $course
. "'";
$row=mysql_fetch_row($result);
$sql = "INSERT INTO registerlist (name, Course, Email, Contact,
Date) VALUES ('" . $name . "', '" . $course . "', '" . $email . "', '" .
$contact . "','" . $date . "')";
$result1= mysql_query($sql, $dbconn);
$result =mysql_query("UPDATE courselist SET $Row['slot'] =
'$Row['slot'] - 1 '");
if ($result1) {
$resultStr = header("Location:blog.php");
}
}
echo json_encode($resultStr);
if the person register the course, the course slot will subract by 1 and student document will be insert into registerlist database.
I hope I did understand correctly: You want to update the courselist table at the same time a record was insert into the registerlist table? This can be done using triggers (https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html , IF both databases run at the same SQL server) and/or table locks (https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html):
Without trigger
Lock table courselist
Insert the record to registerlist
Update table courselist
Release table courselist
With trigger
You need a trigger that locks the table courselist before writing to the registerlist table, and a trigger that updates courselist and releases the lock after writing to registerlist.
In this case you only insert the record into registerlist from your PHP code, and the table locking and courselist update is being done by the triggers within the SQL server.
In any case you can't write to both tables at the same time, there is no SQL statement to do that. But with locks you can simulate such a behavior.
When defining the target table of a SQL statement, you may prepend the tables database name like databaseName.tableName, if the Connection uses a different database per Default.
But aynber from the comments is absolutely right - you should move away from mysql_* asap!
Edit: This SQL example should show how table locking is working (all information about that can be found in the MySQL documentation from the link above):
LOCK TABLES courselist WRITE;
INSERT INTO registerlist …;
UPDATE courselist …;
UNLOCK TABLES;
You'll Need a WRITE lock, since you're going to write to the table. Other reading, writing or locking statements from other sessions are blocked until you release the lock.
A READ lock would prevent the table from being modified by any session. Writing (and write locking) attempts are blocked until you release the lock and all other READ locks from other sessions are released, too.
I am creating a forum service ( https://www.orbitrondev.com/forum/ )
When someone creates a new thread it will execute:
// Example values
$UserID = 23123;
$ForumID = 1;
$ThreadName = 'Example title';
$sQuery = 'INSERT INTO threads (user_id, board_id, topic, time, lastPostUserId, lastPostTime)
VALUES ("' . $UserID . '", "' . $ForumID . '", "' . $ThreadName . '", "' . $time . '", "' . $UserID . '", "' . $time . '")';
The ID is in the column thread_id
Now I have to get the ID (thread_id) of the inserted row. So I can create a post, and to create a post I need the ID.
I thought about getting the last inserted thread id an adding 1 so I have the id, but SQL looks finer :P
How can I know the thread_id value for the newly inserted row?
You should use mysqli::$insert_id.
Where $mysqli is your connection;
$result = $mysqli->query($sQuery);
$lastid = $mysqli->insert_id;
Although you should use prepared statements when inserting data into the database.
Note: You need to have an auto incremented ID field in the database for this to work.
You have;
$oResult = $Database->query($sQuery);
$ThreadID = $oResult->insert_id;
which will not work.
You should use the connection to find the last inserted ID, like this;
$oResult = $Database->query($sQuery);
$ThreadID = $Database->insert_id;
Hope this helps.
You can retrieve the most recent AUTO_INCREMENT value with the
LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function.
These functions are connection-specific, so their return values are
not affected by another connection which is also performing inserts
http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id
used in the last query
http://php.net/manual/en/mysqli.insert-id.php
I host multiple servers for multiplayer games and I am requiring some help with creating a PHP MySQL script.
I have made scripts for the game servers that output a few variables to a php script. These variables include the player name, a GUID number (Game User ID) and a couple other unimportant things. These are sent to the php script every time a player joins the server.
Anyway what I basically need it to do is every time a player joins the server it saves the player name, guid and join date/timestamp to a row in a MySQL table. The player will always have only one GUID code, which is sort of like their cd-key. What I have at this current time:
if ( $action == "save")
{
$name = mysql_real_escape_string($_GET['name']);
$guid = mysql_real_escape_string($_GET['guid']);
}
mysql_query("INSERT INTO `players` (`name`, `guid`) VALUES ('$name', '$guid') ON DUPLICATE KEY UPDATE `last_joined`=CURRENT_TIMESTAMP")or die(mysql_error());
echo "-10";
die();
Now, this works great as it is. But what I need it to do is; if the player comes on the server with a different name, it will log that instance into a new row and if they come on again with the same name it will update the same row with the current time stamp. And for instance, if they change their name back to the first name they use it will update the row that has that name recorded with the current time stamp.
The only thing I have tried is making the 'name' column, a primary key and on a duplicate entry it would update it. However if I did that and another player came on the server with the same name it would just update the last player's data.
So it needs to record every username a player uses.
There's probably quite a simple solution but I've never had the time to learn to MySQL and I need this done soon.
Thanks for any help.
Make the GUID the primary unique key.
Then instead of just inserting the row, check if that guid exists in the database first and then if it does, update the row. If it doesn't then you can insert it.
You can take a shot for this:
$guid = mysqli_real_escape_string($conn, $_GET["guid"]);
$name = mysqli_real_escape_string($conn, $_GET["name"]);
if (!empty($guid) && !empty($name)) {
//Check if the user exists
$sql = "SELECT COUNT(*) AS cnt FROM players WHERE guid = " . $guid;
$res = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($res);
if ($row['cnt']) {
//If yes, update
$sql = "UPDATE players SET `last_joined` = NOW()
WHERE `guid` = " . $guid;
} else {
//If no, insert
$sql = "INSERT INTO players (`guid`, `name`, `last_joined`)
VALUES (" . $guid . ", '" . $name . "', NOW())";
}
mysqli_query($conn, $sql);
echo "-10";
die();
} else {
echo 'Missing parameter';
die();
}
NOTE:
I am using mysqli fucntions, because mysql functions are deprecated. You can use PDO also.
I have an option to send multiple rows into an table, i'm using an foreach to do that:
if (is_array($add['jobname'])) {
$insert = "INSERT INTO job_offers (job_category, status) VALUES ";
foreach ($add['job_name'] as $key => $value) {
$insertedval[] = "
('" . safe($add['job_category'][$key]) . "',
'" . safe($add['status'][$key]) . "')";
}
}
$insert .= implode($insertedval, ",");
$last_id = db_query($insert, '+id?'); //gets the last generated ID, its a function that i created, and working great.
The problem is that i want to get the last ID, and i'm getting, but i'm inserting multiple rows into the database, and i want to get the ID's from all the inserted values, because they are being sent at the same time.
I can't put the $last_id variable inside the foreach loop, what do i do?
ps: i'm using auto increment
Can you try something like this?
$db = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
$db->beginTransaction();
$stmt = $db->prepare('INSERT INTO job_offers (job_category, status) VALUES (?, ?)');
$insertedIds = array();
foreach ($add['job_name'] as $key => $value) {
$stmt->execute($add['job_category'][$key], $add['status'][$key]));
$id = $db->lastInsertId();
array_push($insertedIds, $id);
}
$db->commit();
the ids should be in the insertedIds.
You can't.
Only by saving the the last index id before the inserted data, and than do it again after and select all the ids between that range.
SELECT ID FROM job_offers ID BETWEEN last-before-insert AND last-after-insert
You don't need a custom function to get the last insert id , there is already one built into both php mysqli and php PDO extensions .
As far I know , the last insert id is session aware , meaning you will get the last insert from the current insert requests only .
Get last inset id using PHP PDO
$pdo->lastInsertId();
Get last insert id using mysqli
$mysqli->insert_id;
$pdo and $mysqli are the connection variables
Apologies for the vague title, here's my problem:
The goal of my code is to insert a new row into a table that has an auto-increment field. After the insert, I want to get the value of the auto-increment field that has just been generated.
Here's my table defintion:
CREATE TABLE `EventComments` (
`CommentID` int(11) NOT NULL AUTO_INCREMENT,
`EventID` int(11) NOT NULL,
`OwnerID` int(11) NOT NULL,
`Comment` varchar(512) NOT NULL,
`DateTime` datetime NOT NULL,
PRIMARY KEY (`CommentID`)
) ENGINE=MyISAM AUTO_INCREMENT=68 DEFAULT CHARSET=latin1;
I'm trying to get the value of the CommentID field.
So, here is the php code that issues the insert query and then attempts to get the CommentID value.
<?php
session_start();
ob_start();
include_once 'lib/functions.php';
if(isset($_SESSION['uid'])) {
$eventID = $_GET['evid'];
$ownerID = $_SESSION['uid'];
$comment = $_GET['comment'];
$comment = trim($comment);
$dateTime = date('Y-m-d H:i:s');
$db_connection = database_connect();
if($eventID != null && !empty($comment)) {
$query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment, DateTime)
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";
mysqli_query($db_connection, $query) or die(mysqli_error($db_connection));
$id = mysql_insert_id();
$commentHtml = generateCommentFromData($db_connection, $ownerID, $comment, $dateTime, $id);
echo $commentHtml;
}
}
ob_end_flush();
?>
This code issues the following error in the php logs:
mysql_insert_id() [<a href='function.mysql-insert-id'>function.mysql-insert-id</a>]: A link to the server could not be established...
I also tried explicitly passing the database link. But that gives the following error:
mysql_insert_id(): supplied argument is not a valid MySQL-Link resource...
As a final note, the insert query works. It is definitely inserting a new row with the expected data!
Any insight here would be appreciated!
Thanks
You are using the mysqli extension to connect and run your query, but then you use the mysql (notice the lack of i at the end) extension to get your inserted id, that can't work. While they are both extensions that provide access to mysql, they are also two very different libraries and can't share a connection between each other.
For the record, mysqli is the one you should be using, mysql is the "old" version that does not support new features of mysql >= 4.1
In other words, the solution is to use mysqli_insert_id()
Also, please escape your parameters properly, you can't put the content of $_GET and $_POST variables inside your query unsecured like that. At the very least use mysqli_real_escape_string()
$query = "INSERT INTO meetup.EventComments (EventID, OwnerID, Comment, DateTime)
VALUES (" . mysqli_real_escape_string($eventID)." [...]
For more infos on this, have a look to the numerous questions on this subject, for example this one: How to properly escape a string via PHP and mysql
You probably want to use the mysqli extension equivalent: mysqli_insert_id()
It might work as it is by passing the connection resource but even if it did, it's not good to mix methods from two separate connection classes:
$id = mysql_insert_id($db_connection);
DATETIME is a Data Type in MySQL that's why INSERT query is not working. Use backtick ` instead.
$query = "INSERT INTO meetup.EventComments (`EventID`, `OwnerID`, `Comment`, `DateTime`)
VALUES (" . $eventID . ", " . $ownerID .", '" . $comment . "', '". $dateTime ."')";