my idea is like this 'using sql variables'
Note: id not PK
1st query `select #newvalues := (id - coalesce((select sum(minus) from tbl_name t2 where t2.id < t.id), 0)) from tbl_name t;`
2nd query. `update tbl_name set ab = #newvalues;`
could i get all the rows of #newvalues even though it is just a "select query variable"? because at the moment I could only get the last value of it which is 5.
#newvalues ID *not Primary key
9 | -----------> 9 |
8 | -----------> 8 |
7 | -----------> 7 |
6 | -----------> 6 |
5 | -----------> 5 |
*transfer the row values of #newvalues to the column ID.
First, you would need to get the row into an array in order to loop through it. To do so perform a query and store the results in a variable, then we will use the mysqli_fetch_array() function to turn the query into an array.
$idQuery = "SELECT * FROM table";
$idResult = mysqli_query(/*your database connection*/, $idQuery);
Now for the loop.
while ($row = mysqli_fetch_array($idResult)) {
$query = "UPDATE table SET ID = NewId WHERE id = " . $row['id'];
mysqli_query(/*your database connection*/, $query); }
This should work.
Related
Hi i'm having trouble using the data from a select query inside a insert query.
This is my php code -
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "arestaurant";
$ID = $_GET["Id"];
$QUANTITY = $_GET["Quantity"];
$TABLE = $_GET["Table"];
//Make connection
$conn = new mysqli($servername,$username,$password,$dbName);
// check connection
if(!$conn) {
die("Connection Failed. ".mysqli_connect_error());
}
$sql = "INSERT INTO tableorders (tableNumber,isPaid)
VALUES ('".$TABLE."','0')";
$result = mysqli_query($conn,$sql);
$y = "SELECT orderId from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1 offset 0 ";
$resulty = mysqli_query($conn,$y);
if ($resulty !== false) {
$value = mysqli_fetch_field($resulty);
$orderid = $value['orderId']; < -- error
}
$sqlquery = "INSERT INTO orderitems (orderId, productId, quantity)
VALUES ('".$orderid."','".$ID."','".$QUANTITY."')";
$result2 = mysqli_query($conn,$sqlquery);
?>
but im getting -
Fatal error: Cannot use object of type stdClass as array on line 30.
I have several ways in storing it and then using it again, but i can seem to find the solution.
please help?
This error its because the function mysqli_fetch_field return a object, you maybe wants read http://php.net/manual/es/mysqli-result.fetch-field.php
and this function return info of each column.
change this:
$value = mysqli_fetch_field($resulty);
$orderid = $value->orderId;
Maybe you need use: fetch_assoc
http://php.net/manual/es/mysqli-result.fetch-assoc.php
good luck
If you wants get data of column please use fetch assoc like this:
$y = "SELECT orderId from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1 offset 0 ";
$resulty = mysqli_query($conn,$y);
if ($resulty !== false) {
$fila = $resultado->fetch_assoc()
$orderid = $fila['orderId'];
}
The best solution is this:
https://dev.mysql.com/doc/refman/5.7/en/insert-select.html
You don't need to pull the data out to insert it back. Let the MySQL do it for you.
This is my take on the combined insert-select statement. Would you try it?
$sqlquery = "INSERT INTO orderitems (orderId, productId, quantity)
SELECT orderId, $ID, $QUANTITY from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1";
I drop the offset because I didn't see the purpose of it.
Here is an example:
Imagine that there is table called tasks with many rows and we want to select an id value from it and insert it into this test table together with some external values.
mysql> create table test (id int, order_id int, product_id int);
Query OK, 0 rows affected (0.09 sec)
mysql> describe test;
+------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| order_id | int(11) | YES | | NULL | |
| product_id | int(11) | YES | | NULL | |
+------------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> insert into test select id, 5, 6 from tasks order by id asc limit 1;
Query OK, 1 row affected (0.06 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from test;
+------+----------+------------+
| id | order_id | product_id |
+------+----------+------------+
| 1 | 5 | 6 |
+------+----------+------------+
1 row in set (0.00 sec)
mysql> insert into test(id, order_id, product_id) select id, 5, 6 from tasks order by id asc limit 1;
Query OK, 1 row affected (0.04 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from test;
+------+----------+------------+
| id | order_id | product_id |
+------+----------+------------+
| 1 | 5 | 6 |
| 1 | 5 | 6 |
+------+----------+------------+
2 rows in set (0.00 sec)
mysql>
I hope that it shed some lights on the possibilities of the insert-select method
i am try to update a mysql table with a PHP instance query.
but I do not know how to put the query correctly or whether there is a logical part it works specified side mysql or if i can do with php.
i get the data from a web form with 2 field the ID(It is the autoincrementable ID in MySQL) and a input with the new order.
Update Case 1: Change Order Update Data
ID=3
Imput=5
Original table 1
+--------+---------+
| ID | Order |
+--------+---------+
| 1 | 1 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
| 6 | 6 |
| 7 | 10 |this have a Hole from last registre order need preserve
| 8 | 11 |
+--------+---------+
Table
+--------+---------+
| ID | Order |
+--------+---------+
| 1 | 1 |
| 2 | 2 |
| 3 | 5 |Updated
| 4 | 6 |Updated
| 5 | 7 |Updated
| 6 | 8 |Updated
| 7 | 12 |Update, preserve and continue the hole
| 8 | 13 |Update, and Continue if more record
+--------+---------+
Update Case 2: Inserting a new record and modify the order.
ID=2
Imput=4
Original table 2
+--------+---------+
| ID | Order |
+--------+---------+
| 1 | 1 |
| 7 | 10 |this have a Hole from last registre order need preserve
| 8 | 11 |
+--------+---------+
Table
+--------+---------+
| ID | Order |
+--------+---------+
| 1 | 1 |
| 2 | 4 |record Inserted
| 7 | 10 |preserve no need update
| 8 | 11 |
+--------+---------+
I need some cycles, but do not know what conditions apply.
basics sorry for my example but I am not very expert
Update 1 Legancy
<?php
#Get Values from input Dinamical:
# $i_txt_1 = ID
# $i_txt_3 = New Order
# Attention: this is not the correct syntax for PHP, they are guidelines on what to do at every step, and that must be taken into account for the creation of the string of update.
foreach ($_POST as $key => $value){
${$key} = trim(addslashes(strip_tags($value)));
}
#collector output message
$psmg = '';
#statement prepared for the query updater
$stmtpreUP ="";
#save this variable the current date using some specific function.
$DateUD;
#We keep the variable that is the form that represents the ID
$ID = $i_txt_1;
#first condition
1. search the database if the ID exists we receive the form.
result 0{
throw new Exception You can not modify a nonexistent parameter. Search before Change
}
#second condition
2. if order is the same that the current order display MSG
{
$psmg.='<br>Update was not carried out in the Order';
}
#third condition
3. if check if it exists, any record or ID, with the order comes from the form.
result 0{
update: Create a direct update using the new order and id.
}else{
#Important Step : detecting whether an increase or decrease in the order
4. $GViD = $i_txt_3 - order;
if ($GViD < 0){
#in case is decreasing the order
$stmtpreUP .="UPDATE Table SET Order= $i_txt_3, DateUD= DateUD WHERE ID = $i_txt_1"; #String update for the ID target
#Generate the string updater for the following rows, contemplating that, if a decrease in these rows ID target should be avoided.
5.
GET "SELECT ID, Order FROM Table WHERE Order >= ".$i_txt_3." ORDER BY Order ASC";
$count = $i_txt_3; #need a counter
#Cicle to generate Update String
6.
while ($datos = mysqli_fetch_array($Get)){
#condition to ignore the target ID and update only up to the target ID range, avoid overuse of resources
if($datos['ID']!==$ID AND $datos['ID']<$ID ){
$idUD = $datos['ID'];
$count = ++$count;
$neworder = $count;
#concatenation to the Update String
$stmtpreUP .= "UPDATE table SET Order = ".$neworder.", DateUD ='".$DateUD."' WHERE ID ='{$idUD}';";
}
}
}else{
#in case is Increase the order
$stmtpreUP .="UPDATE Table SET Order= $i_txt_3, DateUD= DateUD WHERE ID = $i_txt_1"; #String update for the ID target
#Generate the string updater for the following rows, contemplating that, if a decrease in these rows ID target should be avoided.
7.
GET "SELECT ID, Order FROM Table WHERE Order >= ".$i_txt_3." ORDER BY Order ASC";
$count = $i_txt_3; #need a counter
#Cicle to generate Update String
8.
while ($datos = mysqli_fetch_array($Get)){
#condition to ignore the target ID and update all the next Order for all the table to preserver spaces into order
if($datos['ID']!==$ID){
$idUD = $datos['ID'];
$count = ++$count;
$neworder = $count;
#concatenation to the Update String
$stmtpreUP .= "UPDATE table SET Order = ".$neworder.", DateUD ='".$DateUD."' WHERE ID ='{$idUD}';";
}
}
}
}
#Run the update of all the statement
9. #function to run mutiple statement updates.
BDupdateM($stmtpreUP);
$psmg.='Datos Actualizado Correctamente';
10. output all MSG
echo $psmg;
?>
Why would you want to make something like that man, you are approaching it the wrong way IMO such a thing will be so expensive (performance wise).
If you want to ORDER BY ID, then by Order you just need to make a SELECT statement like
SELECT * FROM table ORDER BY id,order
<?php
#Get Values from input Dinamical:
# $i_txt_1 = ID
# $i_txt_3 = New Order
# Attention: this is not the correct syntax for PHP, they are guidelines on what to do at every step, and that must be taken into account for the creation of the string of update.
foreach ($_POST as $key => $value){
${$key} = trim(addslashes(strip_tags($value)));
}
#collector output message
$psmg = '';
#statement prepared for the query updater
$stmtpreUP ="";
#save this variable the current date using some specific function.
$DateUD;
#We keep the variable that is the form that represents the ID
$ID = $i_txt_1;
#first condition
1. search the database if the ID exists we receive the form.
result 0{
throw new Exception You can not modify a nonexistent parameter. Search before Change
}
#second condition
2. if order is the same that the current order display MSG
{
$psmg.='<br>Update was not carried out in the Order';
}
#third condition
3. if check if it exists, any record or ID, with the order comes from the form.
result 0{
update: Create a direct update using the new order and id.
}else{
#Important Step : detecting whether an increase or decrease in the order
4. $GViD = $i_txt_3 - order;
if ($GViD < 0){
#in case is decreasing the order
$stmtpreUP .="UPDATE Table SET Order= $i_txt_3, DateUD= DateUD WHERE ID = $i_txt_1"; #String update for the ID target
#Generate the string updater for the following rows, contemplating that, if a decrease in these rows ID target should be avoided.
5.
GET "SELECT ID, Order FROM Table WHERE Order >= ".$i_txt_3." ORDER BY Order ASC";
$count = $i_txt_3; #need a counter
#Cicle to generate Update String
6.
while ($datos = mysqli_fetch_array($Get)){
#condition to ignore the target ID and update only up to the target ID range, avoid overuse of resources
if($datos['ID']!==$ID AND $datos['ID']<$ID ){
$idUD = $datos['ID'];
$count = ++$count;
$neworder = $count;
#concatenation to the Update String
$stmtpreUP .= "UPDATE table SET Order = ".$neworder.", DateUD ='".$DateUD."' WHERE ID ='{$idUD}';";
}
}
}else{
#in case is Increase the order
$stmtpreUP .="UPDATE Table SET Order= $i_txt_3, DateUD= DateUD WHERE ID = $i_txt_1"; #String update for the ID target
#Generate the string updater for the following rows, contemplating that, if a decrease in these rows ID target should be avoided.
7.
GET "SELECT ID, Order FROM Table WHERE Order >= ".$i_txt_3." ORDER BY Order ASC";
$count = $i_txt_3; #need a counter
#Cicle to generate Update String
8.
while ($datos = mysqli_fetch_array($Get)){
#condition to ignore the target ID and update all the next Order for all the table to preserver spaces into order
if($datos['ID']!==$ID){
$idUD = $datos['ID'];
$count = ++$count;
$neworder = $count;
#concatenation to the Update String
$stmtpreUP .= "UPDATE table SET Order = ".$neworder.", DateUD ='".$DateUD."' WHERE ID ='{$idUD}';";
}
}
}
}
#Run the update of all the statement
9. #function to run mutiple statement updates.
BDupdateM($stmtpreUP);
$psmg.='Datos Actualizado Correctamente';
10. output all MSG
echo $psmg;
?>
I have a database , where table contains consecutive duplicate rows . Demo of table with data is as follows.
id name processed
1 xyz 0
2 xyz 0
3 ABC 0
4 ABC 0
I want to delete the consecutive duplicate from this table , and once duplicate is deleted update processed to 1. So that the final table looks like follows.
id name processed
1 xyz 1
3 ABC 1
I am doing it as follow.
SET #v1 := (select group_concat(`id`) from `names` as m1 where 0 < (select count(*) from `names` as m2 where m2.`id` = m1.`id` - 1 and m2.`name` = m1.`name`));
DELETE FROM names WHERE id IN (#v1);
UPDATE names SET `processed`=1 WHERE `processed`=0
The query works fine , but it deletes one row at a time . Please help me on this.I want all the selected rows to be deleted .
Thanks in advance.
As #MarkBaker already wrote in comment, you can try DELETE FROM table WHERE name=name and id>id.
But that's only fix to what already has been done. To prevent that, you should add unique index to name column. That should prevent any duplicates of being added in future.
You can't set unique index when you have duplicates though, so you need clean first :)
You cannot UPDATE and DELETE in the same query. So that pretty much leaves you with this:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,name CHAR(3) NOT NULL,processed TINYINT NOT NULL DEFAULT 0);
INSERT INTO my_table VALUES
(1 ,'xyz', 0),
(2 ,'xyz', 0),
(3 ,'ABC', 0),
(4 ,'ABC', 0);
SELECT * FROM my_Table;
+----+------+-----------+
| id | name | processed |
+----+------+-----------+
| 1 | xyz | 0 |
| 2 | xyz | 0 |
| 3 | ABC | 0 |
| 4 | ABC | 0 |
+----+------+-----------+
SELECT y.* FROM my_table x JOIN my_table y ON y.id = x.id + 1 AND y.name = x.name;
+----+------+-----------+
| id | name | processed |
+----+------+-----------+
| 2 | xyz | 0 |
| 4 | ABC | 0 |
+----+------+-----------+
DELETE y FROM my_table x JOIN my_table y ON y.id = x.id + 1 AND y.name = x.name;
Query OK, 2 rows affected (0.00 sec)
UPDATE my_table SET processed = 1;
Query OK, 2 rows affected (0.00 sec)
SELECT * FROM my_table;
+----+------+-----------+
| id | name | processed |
+----+------+-----------+
| 1 | xyz | 1 |
| 3 | ABC | 1 |
+----+------+-----------+
For PHP and MySQL, If your all data is consecutive pairs then this will work.
$con = mysqli_connect('host', 'user', 'pass', 'db');
$query ="select m1.id from names as m1 where 0 < (select count(*) from names as m2 where m2.id = m1.id - 1 and m2.name = m1.name)";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result)){
$query2 ="DELETE FROM names WHERE id = ".$row['id'];
mysqli_query($con, $query2);
$id = $row['id']-1;
$query3 ="UPDATE names SET `processed`=1 WHERE id = ".$id;
mysqli_query($con, $query3);
}
I checked it and its working fine. Hope it works for you too.
This will not edit your table, but will give you SELECT with desired result:
SELECT min(id) id, name, 1 processed
FROM mytable
GROUP BY name
You can use this in CREATE TABLE newtable AS SELECT ..., and then DROP mytable, and finally to ALTER TABLE newtable RENAME TO mytable.
The DISTINCT keyword can be used to return only distinct (different) values.
Use this query:
SELECT DISTINCT `id`, `name`,`1` AS processed
FROM mytable;
I have the following basic query that selects a PIN from a table, binds it to a variable, and then deletes it from the table.
$sth = $this->db->query("SELECT available_pins FROM pin_list ORDER BY RAND() LIMIT 0,1 ;");
$pinarray = $sth->fetch();
$this->user_pin = $pinarray->available_pins;
$sth = $this->db->prepare("DELETE FROM pin_list WHERE available_pins = ? LIMIT 0,1");
$sth->execute(array($this->user_pin));
My problem: The PIN is selected and echoes fine, but it does not delete from the table. What am I doing wrong?
Also, how would I best add an if statement to catch an error in each of these two cases?
You have a syntax error in your DELETE syntax. LIMIT does not have an offset argument for DELETE.
When selecting the tuple, expand it to include the PK. After you have tied your attribute to a variable, you may delete the tuple by qualifying the where-clause with the PK.
Here is an example. Alas, the example is written in procedural PHP, I haven't coded OO-php for some time now. Sorry about that. Nonetheless, I think the main idea is conveyed. Please let me know otherwise.
Given that the database looks like this:
CREATE TABLE `pin_list` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
`available_pins` CHAR( 8 ) NOT NULL ,
`aux` VARCHAR( 14 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM ;
mysql> select * from pin_list;
+----+----------------+-----+
| id | available_pins | aux |
+----+----------------+-----+
| 1 | 43236543 | f |
| 2 | 43236523 | f |
| 3 | 43266523 | f |
| 4 | 48266523 | f |
| 5 | 48264823 | f |
+----+----------------+-----+
5 rows in set (0.00 sec)
The PHP-script may be written like this:
mysql_connect('mysql_server','user-id','pwd');
mysql_select_db('database-name');
//Select the available pin and its PK.
$query = "SELECT id, available_pins FROM pin_list ORDER BY RAND() LIMIT 0,1";
$rs = mysql_query( $query );
//Select id and available_ping into an array
$pinarray = mysql_fetch_array( $rs );
echo "The pin: " . $pinarray[1]; //Do something with it
//Save the primary key (PK, here: the id-attribute) for use in delete statement
$pk = $pinarray[0];
//Now: delete the pin that you have fetched from the database
echo "DELETE FROM pin_list WHERE id = " . $pk; //echo to debug sql-statements in php.
//Uncomment to delete
//$del_qry = "DELETE FROM pin_list WHERE id = " . $pk;
//mysql_query( $del_qry )
I'm back again. Been searching and trying this for hours... Haven't found an answer or even the right question.
I want to fix a crashed table that I recreated from memory (and the members list in Works) using an query in phpMyAdmin. I need to populate each members total posts.
forum_messages
member_id | message |
--------------------
1 | Hello |
3 | One, Two, Three |
1 | Howdy! |
2 | Here we are again! |
2 | To answer your question... |
forum_members
member_id | posts |
--------------------
1 | 0 |
2 | 0 |
From forum_messages, forum_members should end up looking like this:
forum_members
member_id | posts |
--------------------
1 | 2 |
2 | 2 |
3 | 1 |
Thanks!
Using an INSERT SELECT query, you should be able to rebuild the data you had lost in the forum_members table.
This would return the number of messages per member_id:
SELECT member_id, COUNT(*) FROM forum_messages GROUP BY member_id;
Collating it with an INSERT query puts it into the table instead of displaying the data as it normally would in an SELECT query.
INSERT INTO forum_members (member_id, posts) SELECT member_id, COUNT(*) FROM forum_messages GROUP BY member_id;
try this :
UPDATE forum_members SET posts = (SELECT COUNT(*) FROM forum_messages where forum_messages.member_id = forum_members.member_id GROUP BY forum_messages.member_id)
I think you need just to count messages by members, isn't it?
If so, use this SQL:
TRUNCATE TABLE forum_members;
INSERT INTO forum_members(member_id, posts)
SELECT member_id, COUNT(1) FROM forum_messages GROUP BY member_id;
This should fix it.. Please note that the code is NOT TESTED. You should echo the outcome of the update query to check if it's correct before executing the update query
$get_memberid = "SELECT distinct(member_id) as member_id FROM forum_members;";
$Rget_memberid = mysql_query($get_memberid) or die(mysql_error());
while($row_get_memberid = mysql_fetch_array($Rget_memberid)) {
$arr_get_memberid[] = array( "member_id" => $row_get_memberid['member_id'] );
}
for ($c = 0; $c < count($arr_get_memberid); $c++){
$update_count = "UPDATE forum_members set posts = (SELECT count(member_id) from forum_messages where member_id = '".$arr_get_memberid[$c]['member_id']."') where member_id = '".$arr_get_memberid[$c]['member_id']."';";
$Rupdate_count = mysql_query($update_count) or die(mysql_error());
}