Disable delete button if record exist in multiple table - php

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

Related

How to connect to tables and display their content? (MySQL and PHP)

I have two mysql tables (products and categories). I have some mock data in both tables. Now I need to somehow attach the categories to the products. For example - The product witht he ID 1 should return the following:
| product name | category |
| Monitor | Technology |
I know I have done this bevore, but today I simply can't seem to find the solution to this.
EDIT
This is waht I have so far. The connection works well and I can display the data in a Table.
<?php
// Include database connection
include("connection.php");
// Create variables for later use
$db = $conn;
$tableName = "Produkte";
$columns= ['id_product', 'name_product'];
// Create variable to use in index.php
$fetchData = fetch_data($db, $tableName, $columns);
// The function below feteches data from the tables specified and checks if the colums are emtpy by any chance.
function fetch_data($db, $tableName, $columns) {
// Check db connection
if (empty($db)) {
$message= "Database connection error";
}
// Check if the columns variable is empty and not an array by any chance
elseif (empty($columns) || !is_array($columns)) {
$message="Product Name must be defined in an indexed array";
}
// Check if table name is empty
elseif (empty($tableName)) {
$message= "Table Name is empty";
}
// Else proceed as usual.
else {
$columnName = implode(", ", $columns);
// The query needs to be repalced. Today my SQL stuff is leaving me a bit.
$query = "SELECT p.".$columnName." AS product, c.name_category FROM $tableName p JOIN Kategorie c ON c.id_";
$result = $db->query($query);
if ($result== true) {
if ($result->num_rows > 0) {
$row= mysqli_fetch_all($result, MYSQLI_ASSOC);
$message= $row;
}
else {
$message= "No Data Found";
}
}
// Throw error if error occures
else{
$message= mysqli_error($db);
}
}
return $message;
}
The table products has only 2 columns. An id column and a product_name column.
It's vary basic technics:
// create DBquery using JOIN statement
$query = "
SELECT
p.name AS product, c.name AS category
FROM products p
JOIN categories c ON c.id = p.category_id;";
// get DB data using PDO
$stmt = $pdo->prepare($query);
$stmt->execute();
// show table header
printf('| product name | category |' . PHP_EOL);
// loop for output result as table rows
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
printf('| %-12s | %10s |' . PHP_EOL, $row['product'], $row['category']);
}
Try online

SQL Update Statement not working but the information from row=fetch_assoc() are printed on the screen

I am looping through the rows of the database with fetch_assoc() and I am selecting two columns of it. I check the values of these two columns of each row. If they are between 2 values then I updated a third row as 1(TRUE) if a statement is true. I am creating two connections because there are two statements, the one that selects the information and the other that updates the column that I want to be updated. When I try to print the information in the screen it seems that the SELECT statement works but when I try to UPDATE the column that I want the UPDATE statement does not update the database. Here is my code:
$conn= mysqli_connect("localhost","root","root");
$variablech = 1 ;
$query = "SELECT Client, Info FROM DataTable";
if ($result = mysqli_query($conn, $query)) {
while($row=mysqli_fetch_row($result)) {
if((($row['Client']>=54.055) && ($row['Client']<=54.117) ) && (( $row['Info']>=-4.827) && ( $row['Info']<=-4.317)))
{
$variablech = 0;
$sql= " UPDATE DataTable SET InfoData='$variablech' WHERE Client='".$row['Client']."' AND Info='".$row['Info']."'";
$conn->query($sql);
echo "yes";
}
else
{
$variablech = 1;
$sql= " UPDATE DataTable SET InfoData='$variablech' WHERE Client='".$row['Client']."' AND Info'".$row['Info']."'";
$conn->query($sql);
echo "no";
}
}
}
This should do the trick:
...
$sql= "UPDATE DataTable SET InfoData='".$variablech."' WHERE Client='".$row['Client']."' AND Info='".$row['Info']."'";
mysqli_query($conn, $sql)
...
Suggestion:
Not sure, if you have an auto_increment field in your table. If you do, then select it in select query and then use the same to update the data in update query. That will speed up the database stuff and so is your project.

How to INSERT into 1 table and update the count of another

My Insert query is :
function CreateResult($init_quizz_id,$result_title,$result_image,$result_description) {
$sql = "INSERT INTO result_quizz(init_quizz_id,result_title
,result_image,result_description)
VALUES('$init_quizz_id','$result_title','$result_image','$result_description')";
if ( $GLOBALS['conn']->query($sql) === TRUE) {
echo "Result Added";
$sql2 = "UPDATE 'init_quizz' SET 'results_count' = 'results_count' +1 WHERE 'quizz_id' = '$init_quizz_id'";
$GLOBALS['conn']->query($sql2);
if (!$GLOBALS['conn']->query($sql2)) {
echo ' NO UPDATE';
}
}
}
Lets say i have init_quizz table with the questions, and another table quizz_results. I want to increase the results_count on every quizz when result is added. My result table is hoilding also an init_quizz_id which is the actual ID of the quizz.
Im beginner so im looking for any solution to that.
Thanks
edit: fixed the error on the second query( sql2 ) and getting "not updated" msg. Seems like my second query is completely wrong. Any ideas?
#barmar was right, i found a better solution for my counter instead of UPDATE, i just returning the affected rows which have quizz_id from my results table.
function GetResultsCountByID($quizz_id) {
global $conn;
$sql = "SELECT * FROM result_quizz WHERE init_quizz_id = '$quizz_id'";
$result = $conn->query($sql);
return mysqli_affected_rows($conn);
}

Limit No. Of MYSQL Data

I'm using MySQL to show data on my website: http://www.onlinedealsindia.in. You can see the deals (deal boxes) there but I want to limit them. I want only 50 deals (deal boxes) to show up per page. Clicking the more button would show the next 50 deals.
Below is my code to get data from MySQL:
<?php
$host="localhost";
$username="username";
$password="pass";
$dbname="DB NAme";
$conn=new mysqli($host, $username, $password, $dbname);
if($conn->connect_error)
{
die("error".$conn->connect_error);
}
else { echo "";}
$sql= "SELECT * FROM table ORDER BY p_id DESC";
$results=$conn->query($sql);
if($results->num_rows > 0)
{ while($row=$results->fetch_assoc())
{ $pid=$row["p_id"];
?>
The mechanic you are looking for is called skip and take.
In mySQL you can use the LIMIT to accomplish this. With one parameter it returns that many rows. With two parameters, it will skip the first number in rows and return the number of rows for the second number.
This SQL would return 20 rows:
$sql= "SELECT * FROM table LIMIT 10 ORDER BY p_id DESC";
This SQL would return the ten rows skipping the first 10
$sql= "SELECT * FROM table LIMIT 20,10 ORDER BY p_id DESC";
Documentation and examples of LIMIT can be found here
To make this work for your website just pass a parameter that tells what page you are on and how many rows per page. You can then calculate the two numbers you need for your select statement.
$mysqli = new mysqli($host, $username, $password, $dbname);
if($mysqli->connect_error)
{
die("error".$mysqli->connect_error);
}
else {
echo "";
}
$datas = $mysqli->prepare('SELECT id FROM table LIMIT 50 ');
if($datas)
{
$datas->execute();
$datas->bind_result($id);
while($datas->fetch)
{
$store['id']= $id;
$results[] = $store;
}
return $results;
}
foreach($results as $result)
{
echo $result['id'];
}

PHP PDO Row Counting

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.

Categories