MySQL Auto Increment No Duplicate - php

If I run the below query then use the AUTO_INCREMENT variable to post to table1 right afterwards, what are the chances that 2 users run the query at the same time and obtain identical auto increment values?
Is it very unlikely that this would happen?
$query = "SELECT AUTO_INCREMENT
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'db1'
AND TABLE_NAME = 'table1'";
$result = $link->query($query);
$numRows = mysqli_num_rows($result);
while($var2 = mysqli_fetch_array($result)) {
$autoIncr = $var2['AUTO_INCREMENT'];
}
$query = "INSERT INTO table1(id,firstName)
VALUES('$autoIncr','$firstName')";

Rather like
create table table1
(
id int auto_increment primary key,
fullName varchar(100) not null
);
Then in the inserts
insert table1 (fullName) values('Fred Smith');

Here's my answer to get a unique AI value:
$query = "INSERT INTO table1(id,firstName)
VALUES('','$firstName')";
$result = $link->query($query);
$autoIncr = $link->insert_id; //Gets id of last inserted row

Related

How to get the rank of a row in a MySQL table using PHP and how to store it into a separate variable?

I have been writing the script of a cron job in PHP that is supposed to connect to a text file, get the participantID that is written to it using Java separately, and return details about that participant in a separate text file. The details about that participant are supposed to be their Points, Quantity and Rank out of other participants(which is got using the points that the respective participants have got).
This is the code that I have written so far:
<?php
//connect to mysql database procedurally
$conn = mysqli_connect("localhost","root","","anka");
if(!$conn){
echo "Connection error" . mysqli_connect_error("localhost","root","","anka");
}
$participantid = 0;
$participantid = fopen('performancerequests.txt',"r") or die("Request not taken.");
$content = fread($participantid, filesize("performancerequests.txt"));
file_put_contents("performancerequests.txt","");
//should return rank, points, products left(quantity)
$sql1 = "SELECT points from participants where id='$content'";
$sql2 = "SELECT quantity from products where participant_id='$content'";
$sql3 = "SELECT points, ROW_NUMBER() OVER( ORDER BY points ) RowNumber from participants where id='$content'";
$result1 = mysqli_query($conn, $sql1);
$result2 = mysqli_query($conn, $sql2);
$result3 = mysqli_query($conn, $sql3);
while ($row1 = $result1->fetch_assoc()) {
$points = $row1['points'];
}
while ($row2 = $result2->fetch_assoc()) {
$quantity = $row2['quantity'];
}
while ($row3 = $result3->fetch_assoc()) {
$rank = $row3['rank'];
}
$handle = fopen("performance.txt", "w") or die("File does not exist.");
if(fwrite($handle,$content." "."Points: ".$points." "."Quantity: ".$quantity." "."Rank: ".$rank) == false ){
echo "Error Writing.";
}
?>
The code for the tables in question are also as follows:
CREATE TABLE participants (
id bigint(20),
name varchar(255),
password varchar(255),
product varchar(255),
DOB date,
points int(11),
PRIMARY KEY(id)
);
CREATE TABLE products (
id bigint(20),
name varchar(255),
quantity varchar(255),
rate varchar(255),
description varchar(255),
FOREIGN KEY(participant_id) REFERENCES participants(id),
PRIMARY KEY(id)
);
But when I test and run it, it returns the warning that there's an undefined array key, for the variable $rank. And in the text file, the rank bit is also left blank.
Is there a way I could solve this?
You must match alias in your query to array key:
$sql3 =
"WITH ranked AS(
SELECT id, points, ROW_NUMBER() OVER( ORDER BY points ) RowNumber
FROM participants
) SELECT * FROM ranked WHERE id='$content'";
while ($row3 = $result3->fetch_assoc()) {
$rank = $row3['RowNumber']; // here changed
}
php code online

How do I change a value in a column in a table when I add another table?

How do I change the row value of a column in a table when I add another table?
How do you ask for help?
I have two tables in the database
The first table is called Drug
It consists of three columns:
Sample Table I
// TABLE Drug
DROP TABLE IF EXISTS `Drug`;
CREATE TABLE IF NOT EXISTS `Drug` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`brId` text NOT NULL,
`nameDrug` text NOT NULL,
PRIMARY KEY (`id`)
)
The second table is named brand
Sample Table II
// TABLE brand
DROP TABLE IF EXISTS `brand`;
CREATE TABLE IF NOT EXISTS `brand` (
`idBrand` int(11) NOT NULL AUTO_INCREMENT,
`brandName` text NOT NULL,
`theUse` text NOT NULL,
PRIMARY KEY (`idBrand`)
)
What I need is when you add a row in the brand table, brId is updated in the Drug table to the new idBrand by id in the drug table that was sent
I've done the following code because it does not work
<?php
require_once('include/config.php');
$id = $_POST['id'];
$brandName = $_POST['brandName'];
$theUse = $_POST['theUse'];
$query = "INSERT INTO brand
(brandName,theUse)VALUES('".$brandName."','".$theUse."');";
$insertBrand = mysqli_query($con,$query);
if($insertBrand)
{
$updatDrug = "UPDATE `drug` SET `brId` = new.idBrand WHERE `id` = '".$id."' ;";
$resultEnd = mysqli_query($con,$updatDrug);
if($resultEnd){
$result = 'OK';
echo json_encode($result);
}else{
$resultno = 'NO';
echo json_encode($resultno);
}
}
mysqli_close($con);
?>
After the INSERT, use mysqli_insert_id as the value for brId.
$br = mysqli_insert_id($con);
$updatDrug = "UPDATE drug SET brId = :brid WHERE id = :id";
$stmt = $con->prepare($updatDrug);
$stmt->bind_param('ii', $br, $id);
$stmt->execute();
$stmt->close();
And please avoid SQL INJECTION
Try transaction commit, here is an example
<?php
$db = new mysqli("localhost","root","","test"); //连接数据库
$db->autocommit(false); //设置为非自动提交——事务处理
$sql1 = "INSERT INTO `test`.`test1` (`name` )VALUES ('1' )";
$result1 = $db->query($sql1);
$sql2 = "INSERT INTO `test`.`test2` (`a` )VALUES ('1')";
$result2 = $db->query($sql2);
if ($result1 && $result2) {
$db->commit(); //全部成功,提交执行结果
echo '提交';
} else {
$db->rollback(); //有任何错误发生,回滚并取消执行结果
echo '回滚';
}
$db->autocommit(true);
$db->close();
?>

PHP MySQL Query with NOT LIKE specific id

I have 2 tables. The first one is messages and the second is room. msg_id from messages table is the same as id from room table. What I'm doing is selecting all msg_id and for each of them I wanna run a query that deletes all rooms that their ids dont match with msg_id:
My code:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
while($row = mysql_fetch_array( $result )) {
$me = $row[0]; //$me as a string
$int = (int)$me;//transform $me's value to int
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%" . $int . "%'");}
The $result2 query will delete all entries from room table, no matter the value of $int variable. That means that the check is not working. If I change the $result2 to this i.e.:
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%86%'");
all entries will be Deleted except the room entry with id = 86 (it works fine)
The basic plan is that I must keep all room entries that match their id with msg_id .
DELETE FROM `room` WHERE `id` NOT IN (SELECT `msg_id` FROM `messages`)
if you can't use subquery you can try:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
$ids = [];
while($row = mysql_fetch_array($result)) {
$ids[] = (int) $row[0];
}
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT IN (" . implode(',', $ids) . "));
and PLS don't USE mysql_query it is DEPRECATED
Could you use a subquery?
DELETE FROM ROOM WHERE id not in(SELECT msg_id FROM messages);
Try this query,
delete from 'room' where 'id' not in(select 'msg_id' from 'messages');
if it don't work for you, you can try NOT EQUAL TO query
delete from 'room' where 'id' <>(select 'msg_id' from 'messages');

MySQL Update Query - By Row Number

I'd like to update a row in a MySQL table when a specific row number is reached
This is a little confusing since , the real row number of the record isn't a column in the table.
And there's no question of iterating over rows , since we're not iterating over an array as in mysql_fetch_array()
So , if I'd like to update - say the 3rd row of the table , what would the query be like?
I'm a noob at MySQL
Thanks a ton for your help ! :D
$link = mysqli_connect("localhost", "my_user", "my_password", "my_db");
$query = "SELECT MyColoumn FROM Mytable";
$result = mysqli_query($link, $query);
$row_needed = 3; //Your needed row e.g: 3rd row
for ($i=1,$i=$row_needed,$i++) {
$row = mysqli_fetch_array($result);
}
// now we are in 3rd row
$query = "UPDATE MyColumn FROM MyTable SET MyColumn = '".$MyColumnUpdate."' WHERE MyColumn = '".$row['MyColumn']."' ";
$result = mysqli_query($link, $query);
...
Try this query
UPDATE
tbl a,
(Select
#rn:=#rn+1 as rowId,
tbl.*
from
tbl
join
(select #rn:=0) tmp) b
SET
a.columnName = <VALUE>
WHERE
b.rowId = <rowNumber> AND
a.id = b.id;
NOTE The id column must be a unique one, you can use the primary key of that table...
SQLFIDDLE

How can I add dynamic text from a different table where primary key is a foreign key to adynamic table being shown?

I have here a dynamic table named tb_user with column region_id and institute_id and both ids are primary key of another table tb_region (with column region_name and region_id) and tb_institute (column institute_id and institute_name). I wanted to see region_name and institute_name instead of the ids.
I've used this php script
<?php echo $row_institute['institution_name']; ?>
and query to collect data for tb_institute
mysql_select_db($database_connection_ched, $connection_ched);
$query_institution = "SELECT institute_id, institute_name FROM tb_institute";
$institution = mysql_query($query_institution, $connection_ched) or die(mysql_error());
$row_institution = mysql_fetch_assoc($institution);
$totalRows_institution = mysql_num_rows($institution);
but it seems not to display the correct name of id.
query i used to collect data:
mysql_select_db($database_connection_ched, $connection_ched);
$query_notification = sprintf("SELECT * FROM tb_user WHERE status = 'inactive' ORDER BY date_register ASC", GetSQLValueString($colname_notification, "text"));
$query_limit_notification = sprintf("%s LIMIT %d, %d", $query_notification, $startRow_notification, $maxRows_notification);
$notification = mysql_query($query_limit_notification, $connection_ched) or die(mysql_error());
$row_notification = mysql_fetch_assoc($notification);
if (isset($_GET['totalRows_notification'])) {
$totalRows_notification = $_GET['totalRows_notification'];
} else {
$all_notification = mysql_query($query_notification);
$totalRows_notification = mysql_num_rows($all_notification);
}
$totalPages_notification = ceil($totalRows_notification/$maxRows_notification)-1;
$row_institution['institute_name']
instead of
$row_institute['institution_name']

Categories