insert and update in different database in one php - php

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.

Related

$mysqli-insert_id is not incrementing correctly

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 ?

Get ID of an inserted row in sql

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

MYSQL: Saving various instances of players

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.

Is it possible to update a table using WHERE email = $_SESSION['email']

I want to update an already existing table it only has email and I want to add first name and last name does this code work to do so?
UPDATE table
SET fname='$fname', lname='$lname'
WHERE email= '$_SESSION['email'].';
Or can I also use this
$sql="INSERT INTO $tbl_name(fname, lname)VALUES( '$fname, $lname')" WHERE email= '$_SESSION['email'].';
Your UPDATE has a syntax error (problem with apostrophes.)
INSERT will not update but multiply rows. That is not what you want to have.
Here is my suggested query:
$sql="UPDATE table SET fname='$fname', lname='$lname' WHERE email='".$_SESSION["email"]."'" ;
Fix your quotes, like so:
$sql="INSERT INTO $tbl_name(email) VALUES ( '" . $email . "') WHERE email = '" . $_SESSION['email'] . "'";
Try like this: In case of simple Update Query
$user_email = $_SESSION['email'];
$fname = 'Thierry';
$lname = 'Henry';
UPDATE table
SET fname='$fname', lname='$lname'
WHERE email= '$user_email';
Insertion is not a good idea here. It might duplicate your records.
If you want to be more specific than Go like this: Just providing your general syntax. No real time Syntax:
$user_email = $_SESSION['email'];
$fname = 'Thierry';
$lname = 'Henry';
$check_user = 'SELECT * FROM table WHERE email = "user_email"';
if($check_user)
{
YOUR UPDATE QUERY
}
else
{
YOUR INSERT QUERY
}
In case you are using mysql_ functions you should also escape the input:
$email = mysql_real_escape_string($_SESSION['email']);
Disclaimer for idiots: This does not imply I suggest to use mysql_* functions. Use mysqli or PDO instead.
You should also check against NULL and empty values in your query.
$sql = "REPLACE INTO " . $table . "
SET email='" . $email . "'
WHERE email='" . $email . "'
AND email IS NOT NULL
AND email != ''";
From http://dev.mysql.com/doc/refman/5.0/en/replace.html:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted.
Please don't downvote if this doesn't exactly fit, just use INSERT or UPDATE with the same syntax then.

MySQL - Delete a row, how?

Can anyone show me a query in MySQL that would delete rows from all available columns.
I use this to insert rows:
$sql = "INSERT INTO " . KEYS . " // KEYS is a constant
(key, user_id, time, approved)
VALUES ('" . $randkey . "', '" . $user_id . "', '" . $time . "', '0')";
I need the opposite of this now, delete created rows.
delete from <table> where ....
Keep in mind that the delete statement is always for an entire row.
Using similar syntax sql = "DELETE FROM " . KEYS . " WHERE 1=1";
Replace 1=1 with the conditions for the row you want to delete or it will delete all rows.
Also, it's good to get out of the habit of just dropping variables into SQL as soon as possible, because it will open your code up to SQL Injection attacks. Look into using parameterized queries.

Categories