I've got a query and when I run it, I use rowCount to check if it returns a result. If it does, I echo some text. If not, I redirect the user - this worked fine until.... I tried to check if either rowCount returned a result in the same line of code, like this:
$id = '1';
$check1 = $stmt = $con->prepare("SELECT * FROM table1 WHERE ID=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$check2 = $stmt = $con->prepare("SELECT * FROM table2 WHERE ID=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
if($check1->rowCount() > 0 || $check2->rowCount() > 0) {
echo 'Hello';
}else{
header('Location: index.php');
exit();
}
I've manually gone into table1 and table2 and there is a result there, however when I execute the script above, I'm re-directed to index.php because apparently, there is no result.
I'm wondering if this line of code has any syntax errors:
if($check1->rowCount() > 0 || $check2->rowCount() > 0)
A better approach for you is to use two scalar ,COUNT(*) subqueries and add together.
SELECT (SELECT COUNT(*)
FROM `table`
WHERE `ID` = 1
) +
(SELECT COUNT(*)
FROM `table1`
WHERE `ID` = 1
) AS Result
If either of the table shows result Result will > 1 so you can test for it.
With PDO regular, unnamed, placeholders with "lazy" binding when possible - passing data into execute are simpler to use & will dramatically shorten your code. NOTE the parameters passed in execute() must match those in query thus $id must be passed twice.
I have altered your code
$id = '1';
$stmt = $con->prepare("SELECT (SELECT COUNT(*)FROM `search`WHERE `ID` = ?)
+ (SELECT COUNT(*) FROM `search1`WHERE `ID` = ?) AS Result");
$stmt->execute(array($id,$id));
if($stmt->fetchColumn() > 0){
echo 'Hello';
}else{
header('Location: index.php');
exit();
}
PDOStatement::rowCount() does not return the number of rows returned from a SELECT query. It's for calculating number of rows affected by UPDATE or DELETE queries.
You shoud use SELECT COUNT(*) FROM table1 WHERE ID=? to get what you want, as the docs say (http://php.net/manual/en/pdostatement.rowcount.php)
Related
I use the php operator && to select multiple data so that there is no duplication on mysql.
Does the code that I use below run fine? Is there a more simple use of PHP operators?
$date= date('Y/m/d');
$cekcount = mysql_num_rows(mysql_query("SELECT * FROM `pending_media` where `mediaid`='$dielz'"));
$cekcount2 = mysql_num_rows(mysql_query("SELECT * FROM `media` where `mediaid`='$dielz'"));
$selectcount = mysql_query("SELECT * FROM `media` where `date`='$date' AND `uplink`='$nam'");
$cekcount3 = mysql_num_rows($selectcount);
if($cekcount == 0 && $cekcount2 == 0 && $cekcount3 == 0){
mysql_query("INSERT INTO pending_media VALUES('','$nam','$dielz')");
Upgrade to mysqli, I'll recommend object-oriented syntax because it is nicer to work with.
In accordance with the best practice of "minimize calls to the database", I'll condense your three queries into a single, united SELECT call then check for a non-0 result.
My untested suggestion using mysqli's object-oriented syntax (I did test the SELECT query in PHPMyAdmin):
$query = "SELECT SUM(tally)
FROM (
SELECT COUNT(*) AS tally
FROM pending_media
WHERE mediaid = ?
UNION ALL
SELECT COUNT(*)
FROM media
WHERE mediaid = ? OR (date = ? AND uplink = ?)
) t";
$conn = new mysqli("localhost", "root","","dbname");
$stmt = $conn->prepare($query);
$stmt->bind_param("ssss", $dielz, $dielz, $date, $nam);
$stmt->execute();
$stmt->bind_result($tally);
$stmt->fetch();
if (!$tally) {
$stmt->close();
// insert qualifying data
$stmt = $conn->prepare("INSERT INTO pending_media VALUES ('',?,?)");
$stmt->bind_param("ss", $nam, $dielz);
if ($stmt->execute()) {
echo "Insert Query Error"; // $stmt->error;
}else{
echo "Success";
}
}
I am reading and referencing different posts on how to insert if not exists. This is a good thread but I need some additional help.
I need to add a new record with about 10 columns in it, but only insert it if two columns don't match. I also need to do parameter binding on it.
$query = "INSERT INTO Customers (col1,col2,col3,col4,col5,col6)
SELECT * FROM (SELECT ?,?,?,?,?,?) AS tmp
WHERE NOT EXISTS (
SELECT col1 from Customers WHERE uid=? AND pid=?
) LIMIT 1;"
$results = dbQuery($query,(array($val1,$val2,$val3,$val4,$val5,$val6,$uid,$pid)) ;
What am I doing wrong here?
And here is dbQuery call:
function dbQuery($query,$data) {
global $pdo ;
$stmt = $pdo->prepare($query);
$result = $stmt->execute($data) ;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$error = $stmt->errorInfo() ;
if ($result == false) {
var_dump($error) ;
}
return array($result,$error,$rows) ;
}
"?" parameter placeholders aren't named, they're passed by position, so you can't use them more than once.
You could pass uid/pwd twice; but better is to used named parameters passed as a map
(https://www.php.net/manual/en/pdostatement.execute.php)
$query = "INSERT INTO Customers (uid,pid,col3,col4,col5,col6)
SELECT * FROM (SELECT :uid, :pid, :val3, :val4, :val5, :val6) AS tmp
WHERE NOT EXISTS (
SELECT * from Customers WHERE uid = :uid AND pid = :pid
)";
$results = dbQuery($query,(array("uid"=>$uid, "pid"=>$pid, "val3"=>$val3, "val4"=>$val4, "val5"=>$val5, "val6"->$val6)));
Note using the parameter array means all the parameters come through as strings, which may not be what you want. You would have to use bindParam to set specifically typed values.
Best of all would be a stored procedure that allows you to define parameters, use proper binding, and prevent any accidental datatype mismatches.
This question already has an answer here:
Why does mysqli num_rows always return 0?
(1 answer)
Closed 1 year ago.
I am having some problems with prepared statements in Mysqli and I’m not sure why.
I have a database which currently has 3 rows, which I want to select using a SELECT WHERE query. The query which works in PhpMyAdmin is:
SELECT `totalhits`, `totalmisses`, `date`
FROM `performance`
WHERE `domain` = 'test' AND `profileid` = 1
ORDER BY `date` DESC
This shows all three rows (all have domain = test and profileid=1.)
If I run this with a normal query in Mysqli and hard-coded variables, I get the same result:
$query = $conn->query(“SELECT `totalhits`, `totalmisses`, `date` FROM `performance` WHERE `domain` = 'test' AND `profileid` = 1 ORDER BY `date` DESC”);
echo $query->num_rows; //outputs 3
If I try and run it as a parameter query (as I will be using user entered data), I get 0 rows returned:
$stmt = $conn->prepare("SELECT `totalhits`, `totalmisses`, `date` FROM `performance` WHERE `domain` = ? AND `profileid` = ? ORDER BY `date` DESC");
$domain = 'test';
$profileid = 1;
$stmt->bind_param('si', $domain,$profileid);
$stmt->execute();
echo $stmt->num_rows; //outputs 0
No Mysqli errors are generated by any of these lines (using print_r on the object at each point to check). I also added a $stmt->store_result() line after the execute line but still had the same result (should I be doing this anyway?).
The documentation for mysqli_stmt::num_rows misses some detailed information about using num_rows with prepared statements. The description is rather ambiguous in that it refers only to the need to store the result when using the procedural style, but the object-oriented example makes it clear that you need to call the store_result() method before accessing the num_rows property. This means your code should be something like this:
$stmt = $conn->prepare("SELECT `totalhits`, `totalmisses`, `date` FROM `performance` WHERE `domain` = ? AND `profileid` = ? ORDER BY `date` DESC");
$domain = 'test';
$profileid = 1;
$stmt->bind_param('si', $domain,$profileid);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows; //should now output 3
I am having a problem with the following query that should count Null and Not Empty records in database. I need to use a prepared statement to execute. I have the following code but I cant get the correct output. Any help would be greatly appreciated!
$query = "SELECT UserName, COUNT(NULLIF(TRIM(UserName), ''))
FROM Employee";
$stmt = $db->prepare($query7);
$stmt->execute();
$stmt->store_result();
$numrows = $stmt->num_rows;
$stmt->bind_result($Count);
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch();
echo "Count: $Count";
};
To count non-null and non-empty records, you can do:
SELECT COUNT(*)
FROM Employee
WHERE UserName IS NOT NULL AND UserName != ''
You don't need to use TRIM(UserName), because trailing spaces are ignored when comparing strings.
The full PHP code should be like this:
$query = "SELECT COUNT(*)
FROM Employee
WHERE UserName IS NOT NULL AND UserName != ''";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($Count);
$stmt->fetch();
echo "Count: $Count";
I want to set a variable to use in a mysqli query. This doesn't quite work. Prior to mysqli I used to set query calls. I played around with db->multi_query($sql) with no luck. Anyone out there have an idea how to make this work including a set statement?
$sql = 'SET #rownum := 0;';
$sql .= 'SELECT #rownum :=#rownum + 1 AS Rank, User_Id, COUNT(User_ID) AS Block_Count
FROM Block_Owners;
$stmt = $db->prepare($sql);
$stmt->bind_param('ii', $world, $userId);
// execute the query
$stmt->execute();
Do it in two separate queries:
$db->query('SET #rownum := 0');
$sql = 'SELECT #rownum :=#rownum + 1 AS Rank, User_Id, COUNT(User_ID) AS Block_Count FROM Block_Owners'
$stmt = $db->prepare($sql);
$stmt->bind_param('ii', $world, $userId);
$stmt->execute();
Note, however, that the query you want to run will always return a single row (with Rank = 1) since you are using an aggregate function without GROUP BY.