Sql – Insert value in first empty cell of column and show ID - php

I have a SQL statement that will insert a value into the first empty cell. If I run the PHP script again then it inserts into the next null cell etc.
Problem: I also want to find out the ID of that row, and the value of another column in that row. In the MySQL table below, I want a value inserted in the first ‘null’ of COLUMN A, and also know the ID and value in COLUMN B corresponding to that (i.e. ID= 3 and COLUMN B= 11).
My_TABLE
ID COLUMN A COLUMN B
1 6 78
2 7 90
3 NULL 11
4 NULL 5
5 NULL 123
The following sql statement in PHP script will make it possible to insert value to the first empty cell in COLUMN A:
UPDATE My_TABLE
SET COLUMN A = 83
WHERE COLUMN A IS NULL
LIMIT 1;
Result will be:
ID COLUMN A COLUMN B
1 6 78
2 7 90
3 83 11
4 NULL 5
5 NULL 123
I also want to have an SQL script that will print within PHP (echo) the corresponding values of the ID and COLUMN B of the last updated COLUMN A null value (i.e. ID= 3; COLUMN B= 11).
How do I do that?

Here you go
<?php
// just in case, for comparison
$q = 'SELECT `id`,`colB` FROM My_TABLE WHERE `colA` IS NULL ORDER_BY `id` LIMIT 1';
$row = $pdo->query($q)->fetch(PDO::FETCH_ASSOC);
if ($row) {
// voialà, the value for COLUMN B is now known
list($id, $colB) = $row;
$q = 'UPDATE My_TABLE SET `colA`=? WHERE `id`=?';
$stmt = $pdo->prepare($q);
// voilà, your row is updated
$stmt->execute(array($valueForColumnA,$id));
}
Beware, do not copy and paste whis nilly-willy. Read it, look at it, smell it and understand it. Any questions?

Related

PHP PDO SQL query not finding IS NOT NULL rows

table
-----
id column1
1 some random text
2 more random text
3
4 blah blah
5
6
7
8
9
$sqlData7 = $this->con->prepare("SELECT id, column1 FROM table WHERE column1 IS NOT NULL");
$rowTotal7 = $sqlData7->rowCount();
$attIdArr7 = $sqlData7->fetchAll(PDO::FETCH_COLUMN, 0);
print_r($attIdArr7);
This should return:
Array ( [0] => 1 [1] => 2 [2] => 4 )
but is returning
Array ( )
What am I doing wrong that it is not picking up the not null columns?
I don't think I need an additional boolian column "is_column1_Null" that I can query but after half a day trying to get this to work I am about to add it.
many thanks
You need to call $sqlData7->execute()
<?php
$sqlData7 = $pdo->prepare("SELECT id, column1 FROM `table` WHERE column1 IS NOT NULL");
$sqlData7->execute();
$rowTotal7 = $sqlData7->rowCount();
$attIdArr7 = $sqlData7->fetchAll(PDO::FETCH_COLUMN, 1);
var_dump($attIdArr7);
PHP PDO Online test
You can do write the following query to get the expected result
SELECT id, column1 FROM table column1 IS NOT NULL AND TRIM(column1) <> '';
The above database design suggest that the column is empty and not set to null but can be null also. So I check for two conditions, check if the column is not null and also to check whether it's not empty. I think it's inserting data without any validation, so it's insert empty values too.

Delete rows in MySQL database table based on column parameter

I have JSON data continuously inserted into a DB table but there are some rows which I need to delete concurrently based on the column value. For eg., I need to delete the rows which have a column value (time_min) of more than 90 minutes.
ID time_min
1 50
2 30
3 91
4 40
5 93
6 95
7 40
Here I need to delete rows containing values more than 90 in time_min column.
This is the current code I'm using.
if($time_min >= 91){
$sql = "truncate table_name";
if ($conn->query($sql) === TRUE) {
echo "Rows Dropped";
}
}
It clearly is deleting the entire table values which mess up in the loading of new values.
I would just want the rows that have column value of more than 90 in time_min (column name) to be deleted.
Would appreciate if someone can guide me on this.
You could use a where condition for check the 90 time_min for delete
delete from my_table
where time_min > 90
try this-
DELETE FROM `table_name` where table_name.time_min>90
Use WHERE Clause condition on column in the query
DELETE FROM 'table_name' tbn WHERE tbn.time_min>90

Insert records if not exist to specific columns with special conditions in MySQL

I have a CSV file which i'd like to insert into a table (let's call it my_table).
For this task, I load the CSV file into a new temporary table called temp_table (has the same features/structure as my_table). The values that don't exist should be INSERTED into my_table
However there are certain conditions that must be fulfilled:
if a value in column letter in my_table doesn't exist then:
insert the value in 'letter' into the column letter in my_table
also insert 'num' value into the column num in my_table
if the value 'letter' exists, but the value in 'num' is missing in my_table , UPDATE that record in the column 'num'
Here is an example for a table in temp_table (left) and my_table (right):
temp_table my_table
letter num letter num
1 aab 123 aab 123
2 aac 123 --- --- (both don't exist)
3 bba 234 bba --- (only num doesn't exist)
result my_table:
letter num
1 aab 123
2 aac 123
3 bba 234
*order (id) doesn't matter.
EDIT: so you can see that the value in line 1 isn't inserted to my_table because the value aab already exists.
in the second line, aac doesn't exist and therefore it is inserted together with the value of num.
in the third line, bba needs to be updated, where the column num gets the value.
does anyone knows how to do it in MySQL?
or would it be easier/make more sense to try to write in PHP?
ADDITIONAL:
This is what I came up so far in order to overcome part 1 -
INSERT INTO my_table (letter)
SELECT DISTINCT letter FROM temp_table
WHERE NOT EXISTS
(SELECT * FROM my_table WHERE my_table.letter = temp_table.letter);
The above mentioned does the job partially. It inserts values that do not exists in letter only. But what about part two? inserting the rows of the column num in which rows in letter are missing? Like in row 2 of the example..
for that purpose I tried:
INSERT INTO my_table (letter, num)
SELECT DISTINCT letter, num FROM temp_table
WHERE NOT EXISTS
(SELECT * FROM my_table WHERE my_table.letter = temp_table.letter
AND my_table.num = temp_table.num);
however, that didn’t work as I wanted.
Although it did skip the first row and indeed inserted the row (2) as it should have:
2 aac 123
it however also inserted the row:
letter num
1 aab 123
2 aac 123
3 bba
4 bba 234
as a new row, and that shouldn’t have occurred! because bba already exists and that is the condition for part 3.
so as mentioned before, the value for the column num should be inserted, if and only if the row in column letter EXISTS !!
If you have a UNIQUE constraint on letter then you can use MySQL's INSERT...ON DUPLICATE KEY UPDATE syntax, with a little bit of logic for your num column:
INSERT INTO my_table (letter, num)
SELECT letter, num FROM temp_table
ON DUPLICATE KEY UPDATE
num = COALESCE(num, VALUES(num));

php pdo copy column between tables

I got the two tables(Table1 and Table2):
Table1:
id hits url
1 11 a
2 5 b
3 6 c
4 99 d
5 14 e
Table2:
id url 2014.04.13 2014.04.14
1 a 0 5
2 b 0 1
3 c 0 3
4 d 0 60
5 e 0 10
hi all,
Table1 one contains the actual hits(which are always up-to-date) and Table2 to statistics(which are done every day at midnight). The columns id(unique number) and url are in both tables the same. So they got the same amount of rows.
So i create every day a new column(with the date of today) and copy the column hits from the table 'Table1' into the new created column into the table 'Table2'
First i alter Table2:
$st = $pdo->prepare("ALTER TABLE Table2 ADD `$today_date` INT(4) NOT NULL");
$st->execute();
Then i cache all entries i need from Table1:
$c = 0;
$id = array();
$hits = array();
$sql = "SELECT id, hits FROM Table1 ORDER BY id ASC";
$stmt = $pdo->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$id[$c] = $row['id'];
$hits[$c] = $row['hits'];
$c++;
}
At last i update Table2:
for ($d = 0 ; $d < $c ; $d++)
{
$id_insert = $id[$d];
$sql = "UPDATE DOWNLOADS_TEST SET `$datum_det_dwnloads`=? WHERE id=?";
$q = $pdo->prepare($sql);
$q->execute(array($hits[$d], $id[$d]));
if($q->rowCount() == 1 or $hits[$d] == 0) // success
$hits[$d] = 0;
else // error inserting (e.g. index not found)
$d_error = 1; // error :( //
}
So what i need is to copy(insert) a column from one table to another.
The two tables are having ~2000 elements and the copying as described above takes around 40 sec. The bottleneck is the last part (inserting into the Table2) as i found out.
One thing i found is to do multiple updates in one query. Is there anything i can do besides that?
I hope you realise that at some point your table will have irrational number of columns and will be highly inefficent. I strongly advise you to use other solution, for example another table that holds data for each row for each day.
Let's say you have a table with 2000 rows and two columns: ID and URL. Now you want to know the count of hits for each URL so you add column HITS. But then you realise you will need to know the count of hits for each URL for every date, so your best bet is to split the tables. At this moment you have one table:
Table A (A_ID, URL, HITS)
Now remove HITS from Table A and create Table B with ID and HITS attributes). Now you have:
Table A (A_ID, URL)
Table B (B_ID, HITS)
Next move is to connect those two tables:
Table A (A_ID, URL)
Table B (B_ID, A_ID, HITS)
Where A_ID is foreign key to attribute "A_ID" of Table A. In the end it's the same as first step. But now it's easy to add date attribute to Table B:
Table A (A_ID, URL)
Table B (B_ID, A_ID, HITS, DATE)
And you have your solution for database structure. You will have a lot of entries in table B, but it's still better than a lot of columns. Example of how it would look like:
Table A | A_ID | URL
0 index
1 contact
Table B | B_ID | A_ID | HITS | DATE
0 0 23 12.04.2013
1 1 12 12.04.2013
2 0 219 13.04.2013
3 1 99 13.04.2013
You can also make unique index of A_ID and DATE in Table B, but I prefer to work on IDs even on linking tables.

SQL update multiple rows with different values, without specifying unique key

I need help building a SQL query which searches for an user_id (let's say user_id = 5), but this user_id has multiple row entries, but I need to update each row differently though.
I have an array with data which I want to assign to that user_id. Here is a table example:
id user_id amount txn_id
1 5 10 foo_unique
2 5 5 bar_unique
3 7 15 xyz_unique
4 5 10 123_unique
My array would look something like this:
Array (
[0] => 14
[1] => 6
[2] => 9
)
As you see I have three array values and three rows for user_id 5, now I want to add each value of that array, to the corresponding user_id (5). Note that I have an UNIQUE column named txn_id
After updating the table, it would look like this:
id user_id amount txn_id
1 5 14 foo_unique
2 5 5 bar_unique
3 7 6 xyz_unique
4 5 9 123_unique
Any ideas how I could achieve this?
Thanks.
P.S: I cannot use SQL CASE on this issue.
If you want to update one row with a value, you have to be able to have a unique condition for that row.
Without adding some extra field, or condition to uniquely identify a row, you are out of luck.
You can use the following query:
UPDATE MyTable
SET
amount =
CASE id
WHEN 1 THEN 14
WHEN 2 THEN 6
WHEN 3 THEN 9
ELSE amount -- just in case user_id 5 has records not covered above.
END
WHERE
user_id = 5
The problem is, there is nothing on your array that says which array entry belongs to which database row. If you want to rely just on the orders (of the array indices, and the database ids,), you have to SELECT all rows for the user first, then loop and update a row at a time. Something like this on PHP (and PDO):
$values = array(14, 6, 9);
$dbh = new PDO('mysql:host=localhost;dbname=yourdbname', 'username', 'password');
$selectQuery = 'SELECT id FROM yourtable WHERE user_id = 5 ORDER BY id';
foreach($dbh->query($selectQuery) as $row) {
$id = $row['id'];
$sth = $dbh->prepare("UPDATE yourtable SET amount = :val WHERE id = :id");
$sth->execute(array(
'val' => array_unshift($values),
'id' => $id
));
}
(Code above assumes the number of values on your arrays matches the number of database rows for user_id = 5).
Looking at the problem you only need to have SQL statements.
First is to create two tables:
CREATE TABLE users
user_id int(11) PRIMARY KEY NOT NULL,
username varchar(25),
) Engine = InnoDB;
CREATE table userbalances (
balance_id int(11) PRIMARY KEY NOT NULL,
user_id int(11),
amount decimal(10,2),
CONSTRAINT userid_fk FOREIGN KEY userid_fk(user_id) REFERENCES users(userid)
) Engine = InnoDB;
Then, after you have INSERT(ed) all of the users and userbalances inside the table, all you need to do is create an UPDATE statement to update the amount:
UPDATE userbalances SET amount=? WHERE user_id=? AND balanceid=?
The update should be in a loop. And you should use mysql_query() function to update it with the assigned arrays that you have.
Note:
Both userid and balanceid should be in the WHERE clause of your UPDATE statement because you have multiple transactions inside the userbalances table. Otherwise, it's going to change all of the balances of all the transactions of that user.
Problem update:
If you don't use any SQL Cases on this problem, then your problem is just PHP. You need to find out what is the function for UPDATE(ing) - to update the amounts. As long as your tables are all prepopulated. There might be a function on the program you use to update it.

Categories