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 )
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 have following data in the table..
+-------------+---------------+--------------+
| activity_id | activity_name | main_unit_id |
+-------------+---------------+--------------+
| 1 | DEA | 67 |
| 2 | DEB | 68 |
| 3 | DEC | 68 |
| 4 | fasdfsadf | 74 |
+-------------+---------------+--------------+
i want to add another activity, but before adding i have to make sure that same activity name is not there against an main_unit_id...
I write following query,
$SQL_CHECK_ACTIVITY = mysql_query(
"SELECT count(*) FROM activities " .
"WHERE main_unit_id = '67' and activity_name = 'DEA'"
);
$RESULT_SQL_CHECK_ACTIVITY = mysql_num_rows($SQL_CHECK_ACTIVITY);
echo $RESULT_SQL_CHECK_ACTIVITY;
then it print 1 which means a activity against this project already exists...
$SQL_CHECK_ACTIVITY = mysql_query(
"SELECT count(*) FROM activities " .
"WHERE main_unit_id = '78' and activity_name = 'afsdaf'"
);
$RESULT_SQL_CHECK_ACTIVITY = mysql_num_rows($SQL_CHECK_ACTIVITY);
echo $RESULT_SQL_CHECK_ACTIVITY;
then it print 1 which means a activity against this project already exists...
but there is no record in this case....
If you want to add another activity, but do not want duplicates on main_unit_id, then the right approach is to create a unique index (or constraint) on the field:
create unique index idx_activities_mainunitid on activites(main_unit_id);
If you attempt to insert a duplicate, the insert will fail.
mysql_num_rows will return the number of rows, not the count(*) result.
In the first test, count(*) will return 1 in one row, so the result will be 1.
In the second test, count(*) will return 0 in one row, so the result would still be 1.
You will need to use a fetch function to get the result of count(*) rather than mysql_num_rows.
Edit
I.e. from:
$RESULT_SQL_CHECK_ACTIVITY = mysql_num_rows($SQL_CHECK_ACTIVITY);
To:
list ($RESULT_SQL_CHECK_ACTIVITY) = mysql_fetch_row($SQL_CHECK_ACTIVITY);
Note: The use of the mysql_* functions are considered deprecated and you should instead use something that offers better security and more functionality, such as MySQLi or PDO.
$SQL_CHECK_ACTIVITY = mysql_query("SELECT * FROM activities WHERE main_unit_id = '".$project."' and activity_name = '67' limit 1");
if(mysql_fetch_row($SQL_CHECK_ACTIVITY)) {
echo 'a activity against this project already exists...';
}
else{
}
I'm trying to return 5 unused values from the codes column of the table below and then set used in the related row to 1.
|--- codes ---| | used |
| FIomQVu71l | | 0 |
| 4TW0lwLWNK | | 0 |
| SjzLB2Shzr | | 0 |
| uTWJrtCgh4 | | 0 |
| tLwOwYGz5R | | 0 |
| byEhzYMWJG | | 0 |
| XFBmGzDGIR | | 0 |
I've managed to get the code working to output 5 random values from codes where used = 0
<?php
$sql = "SELECT codes FROM code_table WHERE used =0 ORDER BY rand() LIMIT 5";
$records = mysql_query($sql, $connection);
while($rows = mysql_fetch_array($records)){
echo "Code: " . $rows['codes'] . "<br />";
?>
But now I'm lost as to how to update the used value for each output codes. All of my attempts have updated every single instance of used to 1 rather than just the instances associated with the 5 codes
You could store the rows in a temporary table. Note that this is not entirely concurrency safe. If another query comes between the insert and the update, it might grab the same rows.
CREATE TEMPORARY TABLE IF NOT EXISTS tmp_codes (codes varchar(50));
-- Get five new rows
INSERT INTO tmp_codes
(codes)
SELECT codes
FROM code_table
WHERE used = 0
ORDER BY
rand()
LIMIT 5;
-- Update the five rows
UPDATE code_table
SET used = 1
WHERE codes in
(
SELECT codes
FROM tmp_codes
);
-- Return to application
SELECT codes
FROM tmp_codes;
DROP TABLE tmp_codes;
Example at SQL Fiddle.
You should execute an update query:
$sql = "SELECT codes FROM code_table WHERE used =0 ORDER BY rand() LIMIT 5";
$records = mysql_query($sql, $connection);
$codes = array();
while($rows = mysql_fetch_array($records)){
echo "Code: " . $rows['codes'] . "<br />";
$codes[] = "'" . $rows['codes'] . "'";
}
$updateSql = "UPDATE code_table SET used = 1 WHERE codes in(" . implode (',' , $codes ) . ")";
$res = mysql_query($updateSql, $connection);
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.
How can I sort values from SQL output by an external condition or e.g. the order of added WHERE conditions?
First I generate multiple ID's with a "json_decode foreach loop"
$itemid = '';
$arr = json_decode($string,true);
foreach($arr['feed']['entry'] as $val)
{
$itemid .= " OR `item_id` = ".$val['id']['att']['ix:id'];
}
The output is e.g. (simplified)
`item_id` = 2
OR `item_id` = 3
OR `item_id` = 1
Here the order of the output is important for me. 2 is the ID of the first position, 3 of the second position and so on.
In the next step I use all IDs in a MySQL statement to pull information for each IDs
$sql = "
SELECT *
FROM `itemtable`
WHERE $itemid
";
Which is more readable:
$sql = "
SELECT *
FROM `itemtable`
WHERE `item_id` = 2
OR `item_id` = 3
OR `item_id` = 1
";
The SQL output is now in the order of the IDs ASC
+-------+-----------+
| ID | INFO |
+-------+-----------+
| 1 | something |
+-------+-----------+
| 2 | something |
+-------+-----------+
| 3 | something |
+-------+-----------+
But I need the Info in the order how the IDs where generated by the json_decode:
+-------+-----------+
| ID | INFO |
+-------+-----------+
| 2 | something |
+-------+-----------+
| 3 | something |
+-------+-----------+
| 1 | something |
+-------+-----------+
I am outputing the received data with another foreach loop in the same php script:
$output = '';
foreach ($xpdo->query($sql) as $row) {
$output .= $row['ID']
.$row['INFO']
."</br>";
}
return $output;
How can I get the output into the order of the json_decode? Actually I dont mind weather the sorting happens in the SQL statement or in PHP.
EDIT : SOLUTION from Fluffeh
Modified the json_decode to + adding an IF condition for the first entry to remove the "union all" here.
$itemid = '';
$arr = json_decode($string,true);
foreach($arr['feed']['entry'] as $val)
{
$itemid .= "union all
SELECT * FROM `itemtable`
WHERE `item_id` = ".$val['id']['att']['ix:id'];
}
You technically can't, but if the query isn't TOO bad, you could write some code to do this:
$sql = "
SELECT *
FROM `itemtable`
WHERE $itemid1
union all
SELECT *
FROM `itemtable`
WHERE $itemid2
";
If you put some PHP to join the queries together it will work quite easily.
When you run union queries, the data will be returned in the order of the queries themselves.