PHP PDO SQL query not finding IS NOT NULL rows - php

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.

Related

MYSQL: List all column names where their values = "Yes"

I have a table like so:
User_Id Column1 Column2 Column3
1 Yes No Yes
2
I want to use mysql query to list all the column names (there are more than 3) which match the User_Id '1' and have a value of 'Yes'.
I get an error:
Trying to get property 'num_rows' of non-object
Here is what I have tried:
<?php $myStats = $mysqli->query("SELECT COLUMN_NAME FROM user_services.columns WHERE myColumn = 'Yes'");
if ($myStats->num_rows > 0) {
// output data of each row
while($row = $myStats->fetch_assoc()) {
$rows[] = $row; }
return $rows; ?>
Please can someone show me where I am going wrong?
Thanks in advance.
The CONCAT_WS function comes in handy here:
SELECT CONCAT_WS(',', IF(Column1='Yes', 'Column1', NULL),
IF(Column2='Yes', 'Column2', NULL),
IF(Column3='Yes', 'Column3', NULL)) AS columns
FROM user_services.columns
WHERE User_Id = 1;
If you have more than 3 columns, then you may add more terms to above CONCAT_WS call. Your problem mainly seems to be a SQL one, so I won't add any PHP code.
Note that your design might be better off if your column strings were spread across rows, rather than columns. For instance, consider the following alternative:
User_Id | number | val
1 | 1 | Yes
1 | 2 | No
1 | 3 | Yes
Then, if you wanted all column numbers which were yes for user 1, you could simply do:
SELECT
User_Id,
GROUP_CONCAT(number ORDER BY number) columns
FROM yourTable
WHERE
User_Id = 1
GROUP BY
User_Id;

PHP Mysql always NEED to return 5 rows even 3rows present in table

Hi i need 5 rows count always in Mysql select query
I My current output is
my query
----------------------
$query = mysql_query("select * from table_name where MOBILE='$mobile_no' order by ID LIMIT 5 ");
----------------------
Result
----------------------
ARUN - 987654321
VINO - 987654321
RAJA - 987654321
-------------------
But I need like this (Need to return empty rows)
----------------------
ARUN - 987654321
VINO - 987654321
RAJA - 987654321
0 - 0
0 - 0
-------------------
So that I can create html table row (always 5 rows) text box with empty value inside the while loop ----- while($row=mysql_fetch_array($query))
You can use a loop in php and a counter in the loop. If the count is less then 5, then you fill the text box with nothing. It will give you something like that
$count = 0;
while($row=mysql_fetch_array($query)) {
// Fill your text box
$count+=1;
}
for($i=count; $i <= 5; $i++) {
// Fill your text box with empty string or whatever.
}
Since you requested a sql solution here it is: (but I do not recommend using it)
SELECT *
FROM (SELECT id, column1
FROM table_name
WHERE mobile = '$mobile_no'
UNION ALL
SELECT NULL, NULL FROM DUAL
UNION ALL
SELECT NULL, NULL FROM DUAL
UNION ALL
SELECT NULL, NULL FROM DUAL
UNION ALL
SELECT NULL, NULL FROM DUAL
UNION ALL
SELECT NULL, NULL FROM DUAL)
AS tab
order by tab.ID LIMIT 5
but you need to explicitly select all the columns from your table and in the select statements add as many NULL columns as you selected in your main statement. I didn't test it since I don't know your columns
simply add 2 more textboxes in html page. and not send any value or send null values in your database

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

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?

MYSQL returning duplicate rows

I have a Database table in MYSQL, it looks like this:
Project_ID user_ID name
11 1 fred
11 2 rick
11 1 fred
I want to get the names in the table, but when I display it I get the same name twice because the user_ID 1 appears twice in the table. I tried to display it with GROUP BY and SUM, but I don't want to do it this way. How do I get it not to return duplicate rows?
Use DISTINCT
SELECT DISTINCT user_ID
, verschil_ma
FROM project_uren
WHERE project_ID = 11
GROUP BY user_ID
Point 1 is that should the user be assigned to the project twice?
Point 2 - Use the DISTINCT keyword to return only unique records - http://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.html
SELECT DISTINCT user_ID
FROM TABLE
WHERE Project_id = 11
That will return you 1 and 2 (You won't get 1 twice)
Thanks
$results = // query
$results = array_unique($results);

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