i want to check the rows if there are any events that are binded to a host with host_id parameter, everything is well if there is not any events binded to a host, its printing out none, but if host is binded to one of the events, its not listing the events, but if i remove the codes that i pointed below with commenting problem starts here and problem ends here, it lists the events. I'm using the fetchAll function above too for another thing, there is not any such that error above there, but with the below part, it's not listing the events, how can i fix that?
Thanks
try
{
$eq = "SELECT * FROM `events` WHERE `host_id` = :id AND `confirmed` = '1' ";
$eq_check = $db->prepare($eq);
$eq_check->bindParam(':id', $id, PDO::PARAM_INT);
$eq_check->execute();
//problem starts here
$count3 = $eq_check->fetchAll();
$rowCount = count($count3);
if ($rowCount == 0)
{
echo "None";
}
//problem ends here
while($fetch = $eq_check->fetch (PDO::FETCH_ASSOC) )
{
$_loader = true;
$event_id = $fetch['event_id'];
$event_name = $fetch['event_name'];
$link = "https://www.mywebsite.com/e/$event_id";
echo "<a target=\"_blank\" href=\"$link\"><li>$event_name</li></a>";
}
}
catch(PDOException $e)
{
$log->logError($e." - ".basename(__FILE__));
}
Thank you
You can't fetch twice without executing twice as well. If you want to not just re-use your $count3 item, you can trigger closeCursor() followed by execute() again to fetch the set again.
To reuse your $count3 variable, change your while loop into: foreach($count3 as $fetch) {
The reason that it is not listing the events when you have your code is that the result set is already fetched using your fetchAll statement (The fetchAll doesn't leave anything to be fetched later with the fetch).
In this case, you might be better off running a select count(*) to get the number of rows, and then actually running your full query to loop through the results:
An example of this in PDO is here:
<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
Note that you cannot directly use rowCount to get a count of rows selected - it is meant to show the number of rows deleted and the like instead.
Related
I am trying to get rows from a table when a condition is satisfied (status = 'no transit') but nothing shows up even when rows are supposed to show up (count is 1 and more).
if($query['num'] == 0){
echo "<p>No shopping orders on transit</p>";
}else{
$sql = "SELECT *, FORMAT(total, 0) AS total, FORMAT(grand_total, 0) AS grand_total FROM shipping_details WHERE status = 'no transit' ORDER BY order_id DESC";
foreach ($db->query($sql) AS $query){
echo" Show some results ";
$select = "SELECT * FROM shipping_order WHERE order_id = :order_id";
foreach ($db->query($select, array('order_id' => $query['order_id'])) AS $items){
echo"
Some results
";
//Foreach ends
}
}
}
You don't show enough that we can tell which codebase you use to connect to your DB (MySQLi, mysql_, or PDO), so the code below may need some tweaking.
The problem is basically that you never retrieve your database results. Instead you try to loop through the query execution itself.
Change
$sql = "SELECT *...";
foreach ($db->query($sql) AS $query)...
To
$sql = "SELECT *...";
$result = $db->query($sql); //execute the query
if(!$result) die($db->error); //exit and show error if query failed
//now we can fetch the results one at a time and loop through them
//this line may need to be adjusted if you're not using MySQLi
while($row = $result->fetch_assoc())...
Within the while loop, $row will contain the values from the DB record. Use print_r($row) to learn its shape.
It is not working, because you forgot to use prepare and execute methods from pdoStatemnt class.
See below:
$stmt = $db->prepare("SELECT * FROM shipping_order WHERE order_id = :order_id");
$stmt->execute(array('order_id' => $query['order_id']));
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)){
echo"
Some results
";
//Foreach ends
}
I'm working on another class project and what I want to do is check the database is a row exists.
I've seen several different methods throughout the forum and not one of them seem to work. I've spent roughly 12 hours on this one thing and it's becoming a time sink.
Here is the last iteration of the code I've tried :
$ciid = $_POST['categoryid'];
$check = $db->prepare("SELECT categoryid, imgid FROM catType WHERE categoryid = $ciid AND imgid = $imgID ");
$check->bindParam(categoryid,$ciid);
$check->bindParam(imgid,$imgID);
$check->execute();
if($check->rowCount() > 0 ){
echo "dqowdhnoqwhd";
} else {
/*run working insert */
}
/* the form that passes the $_POST value */
echo "<p><input type=\"checkbox\" name=\"catname[]\" value=\"".$row['categoryid']."\" />" . $row['cName'] . " </p>";
echo "<p><input type=\"hidden\" name=\"".$imgID."\" value=\"".$imgID."\"/></p>";
As it stands now, I get no errors but it also doesn't tell me that the record is already in the database. When I add a new record , it just duplicates it.
the array :
Array
(
[catname] => Array
(
[0] => 1
)
[111] => 111
[icud] => update category
)
I ran the query in phpMyAdmin and the formula worked for what I wanted it to do.
Your code (e.g. bind_param() usage) suggests you want to use a paramaterized query, but you are not leaving any places in the query for the parameters you try to bind. Try this instead:
$ciid = $_POST['categoryid'];
$stmt = $db->prepare("SELECT COUNT(*) FROM catType WHERE categoryid = ? AND imgid = ?");
$stmt->execute(array($ciid, $imgID));
$count = $stmt->fetchColumn();
if($count > 0) {
echo "dqowdhnoqwhd";
} else {
/*run working insert */
}
Note from the documentation about numRows():
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
Instead, since you're not fetching anything useful from the database you can just do a COUNT() of the rows that match. The fetchColumn() function will pull the first column of the next row in the result set; handy for pulling a single value out.
What I didn't do was run a foreach loop on the array items that was holding the categoryid. So everything that I may have tried for the past , many hours wouldn't have worked. here is my solution, please feel free to suggest improvements
n = $_POST['catname'];
foreach($n as $row => $value){
$para = $value;
}
$param = $imgID;
$check = $db->prepare("SELECT imgid , categoryid FROM catType WHERE imgid = $param AND categoryid= $para");
$check->execute();
$count = $check->fetchColumn();
//echo var_dump($check);
if($count > 0) {
echo "Category already added";
I have here mysql records display in html table with delete button. What I need to do is disable the delete button if record is exist in both database table.
How I can disable the delete button per row if record already exist in both table? any help will appreciate.
$search = $mysqli1->real_escape_string($_POST['bid']);
$search = preg_replace("/[^A-Za-z0-9 ]/", '', $search);
$search = $_POST['bid'];
$res = $mysqli1->query("select * from code WHERE item LIKE '%$search%' OR item_code LIKE '%$search%' OR cat_code LIKE '%$search%' order by item_code ASC");
while($r = $res->fetch_assoc()){
echo "<tr>
<td><a href='#' id='".$r['id']."' class='del'><img src='../images/del.png'></a></td>
</tr>";
}
throw in a simple if() statement
connected with the both queries
in pdo you use the ->rowCount()
not sure in mysqli
so this logic you'd need
query1 = counted rows in table1
query2 = counted rows in table2
as if you said if it exists in both tables it should hide it so you're going to work with an if-or statement
if(query1 == 0 || query2 == 0){
//show your button
}
what here stands is simple:
if(query1 equals 0 rows OR query2 equals 0 rows){
//show your button
}
//While you don't put up the else with something else it won't show anything
//so if there are the value of 1+ rows in both query1 and query2 this won't show anything
if you want me to provide a pdo example just reply
edit:
PDO Class to make it easier to connect
class Database extends PDO
{
private $db;
public function Database($host, $user, $pass, $db) {
try {
$this->db = new PDO("mysql:dbname=".$db.";host=".$host.";", $user, $pass);
} catch(PDOEXCEPTION $e) {
die('An error has occurred! [Code: '.$e->getCode().']! <br/>More info: ['.$e->getMessage().']!');
}
}
public function runQuery($query) {
try{
return $this->db->query($query);
} catch(PDOEXCEPTION $e) {
die('An error has occurred! [Code: '.$e->getCode().']!<br/>More info: ['.$e->getMessage().']!');
}
}
}
Now the row counting: updated there was a little mistake by the && and the 2x query1 check
$consite = new Database('DBHost','DBUsername','DBPassword','DBName');
$query1 = $consite->runQuery("SELECT * FROM TABLE1");
$query2 = $consite->runQuery("SELECT * FROM TABLE2");
if($query1->rowCount() == 0 || $query2->rowCount() == 0) {
//do your while statement to loop through it
//if you done your while statement it only shows the delete button
//for items that are NOT in both tables
}
sorry I was too lazy to add the while statement ;)
if I am correct you can check from multiple tables in a sql query so you can do it with 1 query if you make the multi check following 1 query!
edit:
Logical steps for this question:
1) Connect to the database
2) Make a query for table1
3) Count the entries(records) from table1
4) Make a query for table2
5) Count the entries(records) from table2
6) Check if one of them equals 0
7) if one of them equals 0 entries (records(rows)) then show the button
I have two php files. They each have a different query in them. Both of them work. Then I have one file where I include both files inside of it. The queries work on their individual pages, but in the page where they are both included only the first query works. They look something like this (The first one uses * because I pull out every row)
include 'connect.php';
$query = "SELECT * FROM table ORDER by jid DESC";
$ex = $mysqli->query($query) or die(mysqli_error());
$row_cnt = mysqli_num_rows($ex);
if ($row_cnt > 0) {
/* fetch associative array */
while ($row = $ex->fetch_assoc()) {
echo $row["one"] . $row["two"] . $row["three"] . $row["four"];
}
$result->free();
}
$mysqli->close($mysqli);
The second one is like this
include 'connect.php';
$q = "SELECT one, three FROM table ORDER by jid DESC";
$d = $mysqli->query($q) or die(mysqli_error());
$row_cnt = mysqli_num_rows($d);
if ($row_cnt > 0) {
/* fetch associative array */
while ($row = $d->fetch_assoc()) {
echo $row["one"] . $row["three"];
}
$result->free();
}
$mysqli->close($mysqli);
Then the file that includes them is just two includes like include ' ';
How do I get both queries to work on the one page?
add value in array, like this:
include 'connect.php';
$q = "SELECT one, three FROM jokes ORDER by jid DESC";
$d = $mysqli->query($q) or die(mysqli_error());
$row_cnt = mysqli_num_rows($d);
$values = array();
if ($row_cnt > 0) {
/* fetch associative array */
while ($row = $d->fetch_assoc()) {
$values[0][] = $row["one"];
$values[1][] = $row["two"];
$values[2][] = $row["three"];
$values[3][] = $row["four"];
}
$result->free();
}
$mysqli->close($mysqli);
... after, use foreach for print the value
I have not tested
How do I get both queries to work on the one page?
Just run them one after another like everyone does.
If something goes wrong - debug your code, like everyone does. Read all the error messages and act accordingly.
i hope someone can help about to scream!
basically I am trying to do a few things with the statement below;
First i want to check if the user id exists in member_categories_position.
If it Does i want then to exclude all entries from the second statement where member_id equals all results from the first statement
the third statement is the else statement that displays if the member_id is not present in the member_categories position.
PROBLEM - the result from the first system loops fine, however when i try and insert into the second statement (!='$memid') is produces no results and has no effect. I think the problem is that $memid is a looped result.
How do i get the second statement to say that any member_id that is in member_categories_position will not show in that statement?
$sql2 = "
SELECT *
FROM member_categories_position a
JOIN member_users b
ON b.id = a.member_id";
$rs2 = mysql_query($sql2);
while ($row = mysql_fetch_array($rs2))
{
$memid = "".$row['member_id']."";
}
if(mysql_num_rows($rs2) != 0)
{
$new= "
SELECT *
FROM member_categories
JOIN member_users
ON member_categories.member_id=member_users.id
JOIN member_config
ON member_categories.member_id=member_config.member_id
WHERE
member_categories.categories='$category'
AND member_categories.member_id !='$field'
GROUP BY member_config.member_id
ORDER BY RAND() limit 0,42";
$rs = mysql_query($new);
while ($row = mysql_fetch_assoc($rs))
{
echo "result excluding member ids from the first statement";
}
echo "<div class=\"clear\"></div>";
}
else
{
$new= "
SELECT *
FROM member_categories
JOIN member_users
ON member_categories.member_id=member_users.id
JOIN member_config
ON member_categories.member_id=member_config.member_id
WHERE
member_categories.categories='$category'
GROUP BY member_config.member_id
ORDER BY RAND() limit 0,42";
$rs = mysql_query($new);
while ($row = mysql_fetch_assoc($rs))
{
echo "Result with all member ids";
}
echo "<div class=\"clear\"></div>";
} } <-- (second is a stray from original post)
$memid is not in scope since it appears to be defined inside the loop. Try defining $memid = ''; at the top of your script.. like this.
$memid = '';
$sql2 = "
SELECT *
That way it will be defined when you use it below..