Delete Row Result SQL Query - php

I am new in PHP. I am android developer and does not know PHP enough. I have developed one function which provide me numbers from MySQL database. I want delete that numbers instant as soon as it pass me. I am currently doing it like below
function getAllNumbers() {
require_once("includes/conf.php");
global $conn;
$sql = "SELECT number from number_list WHERE server=1";
$result = $conn->query($sql);
$data = array();
if($result) {
while($row = $result->fetch_row()) {
array_push($data, $row[0]);
$delete = "DELETE number from number_list WHERE server=1";
$result = $conn->query($delete);
}
}
$response["data"] = $data;
return $response;
}
My Table Structure is like below
id int(11) NO PRI NULL auto_increment
name varchar(50) NO NULL
number varchar(50) NO NULL
server int(10) NO 0
status int(1) NO -1
last_act timestamp NO CURRENT_TIMESTAMP
user_id int(11) NO MUL NULL
created_at timestamp NO CURRENT_TIMESTAMP
disable int(11) NO 0
notify int(1) NO 1
fcm varchar(500) NO NULL
But I am feeling that if there any new number arrive in database between number select query and delete query it will delete it without select number in first query. So I am looking to delete only rows which get selected in first query. Let me know if there anything I need to change in my codes.
Thanks a lot :)

So if you select the id in the first query as that is the unique key you can use that to delete just this row
function getAllNumbers() {
require_once("includes/conf.php");
global $conn;
$sql = "SELECT number,id from number_list WHERE server=1";
$result = $conn->query($sql);
$data = array();
if($result) {
while($row = $result->fetch_row()) {
$data[] = $row[0];
$id = $row[1];
$delete = "DELETE number from number_list WHERE id = $id";
$result = $conn->query($delete);
}
}
$response["data"] = $data;
return $response;
}

Related

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();
?>

MySQL Auto Increment No Duplicate

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

Solve with only one query?

I have the following table:
CREATE TABLE list(
country TINYINT UNSIGNED NOT NULL,
name VARCHAR(10) CHARACTER SET latin1 NOT NULL,
name_index INT UNSIGNED NOT NULL,
UNIQUE KEY(country, name), PRIMARY KEY(country, name_index)) ENGINE = INNODB
I want to:
Given: ($country, $name, $new_index)
Check if a row with country = $country && name = $name exists.
If the row exists, get the index $index = name_index.
If the row doesn't exist, add it and then get the index.
I can do the following using many queries, but I am looking for an efficient way to do it, using only one query. Is this possible?
It's not possible with only one query.
You CAN do this:
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
$sql = "INSERT INTO (your table) (country, name)
VALUES('$country','$name')";
$query = mysql_query($sql);
$check = mysql_num_rows($query);
if($check > 0) {
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
echo "Error occured while trying to insert new row";
}
}
Hope this helps :).

Move with php one row to another in database tables

i'm using php to make some mods on my database, i have two identical tables and i want to move one row from the first table to the second one how can i do that using pure php and mysql.
that is how my tables looks like
CREATE TABLE users (
username varchar(30) primary key,
password varchar(32),
userid varchar(32),
userlevel tinyint(1) unsigned not null,
email varchar(50),
timestamp int(11) unsigned not null
);
and here is my php code so far
function procMoveUser(){
global $session, $database, $form;
/* Username error checking */
$subuser = $this->checkUsername("user");
/* Errors exist, have user correct them */
if($form->num_errors > 0){
$_SESSION['value_array'] = $_POST;
$_SESSION['error_array'] = $form->getErrorArray();
header("Location: ".$session->referrer);
}
/* move the user */
else{
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$subuser'";
$result = $database->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO".TBL_USERSDONT."VALUES ($array['user'], $array['password'], $array['userid'] , $array['userlevel'] , $array['email'] , $array['timestamp'])";
$second_result = $mysqli->query($second_query);
if($second_result){
// it worked!
$q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";
$database->query($q);
}
}
}
}
}
First, SELECT * FROM the first table for the row that you want to move. Then, as suggested above, run an INSERT statement with the values from the first table.
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'";
$result = $mysqli->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO second_table VALUES ($array['user'], $array['something'])";
$second_result = $mysqli->query($second_query);
if($second_result){
// it worked!
}
}
}
Maybe this will help: Copy an existing MySQL table to a new table

MySQLi query to get maximal id in the table?

$mysqli = new mysqli("localhost","root","","mydatabase");
if ($result = $mysqli->prepare("SELECT MAX(`id`) AS `id` FROM `mytable` WHERE `row1`=? OR `row2`=?"))
{
$id = 2;
$result->bind_param("ii",$id,$id);
$result->execute();
$result->bind_result($max);
$result->close();
var_dump($max);
}
$mysqli->close();
Unfortunately this code always showing NULL, can u folk explain me how to reach a result?
updated:
in console mode staff like this works great. field id is int and incremental (as PRIMARY INDEX), other fields it's just a rows with a different int values, I cant change anything.
updated:
Well, seems I found the solution:
$mysqli = new mysqli("localhost","root","","mydatabase");
if ($result = $mysqli->prepare("SELECT MAX(`id`) AS `id` FROM `mytable` WHERE `row1`=? OR `row2`=?"))
{
$id = 2;
$result->bind_param("ii",$id,$id);
$result->execute();
$obj = $result->get_result()->fetch_object();
$max = $obj->id;
$result->close();
var_dump($max);
}
$mysqli->close();
this is it.
I figured it out this way:
$result = mysqli_query($con, "SELECT * FROM `TableName` ORDER BY `PID` DESC LIMIT 1");
$row = mysqli_fetch_array($result);
$pidmax=$row['PID'];
You still need to call fetch, as max will only be available after that point. See doc: http://php.net/manual/en/mysqli-stmt.bind-result.php
$result->bind_result($max);
/* fetch values */
while ($result->fetch()) {
printf("Max ID %i\n", $max);
}
$result->close();

Categories