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
Related
I have one table called Master and it has four columns called id, A, B and C.
When I update the table, I need to modify the specific single column that a user selected. For example, if a user selected column A then only A records will get updated in the database. If the user selects C then only C records will updated.
Below is the code I tried, but it is updating all columns. Would you help me in this?
$column_name=$row['column_name'];//A,B,C
if (isset($result->num_rows) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$A=$row['A'];
$B=$row['B'];
$C=$row['C'];
}}
UPDATE Master SET $column_name='$A'+20, $column_name='$B'+30, $column_name='$C'+50 WHERE user_id='$id'";
Although your requirement is not fully clear to me so then i think it
will be helped you to meet your requirement. It is a dynamic solution. If it's not you can clarify your requirement i will must be try my best to resolve it. Thanks for asking.
* table schema is stakcoverflow
* table name is master_tbl
* fields name
id | a | b | c
<?php
$myHost = "localhost"; // use your real host name ex. myDomainName.com
$myUserName = "root"; // use your real login user name ex. myUserName
$myPassword = ""; // use your real login password ex. myPassword
$myDataBaseName = "stakcoverflow"; // use your real database name ex. myDataBaseName
$con = mysqli_connect( "$myHost", "$myUserName", "$myPassword", "$myDataBaseName" );
if( !$con ) // == null if creation of connection object failed
{
// report the error to the user, then exit program
die("connection object not created: ".mysqli_error($con));
}
if( mysqli_connect_errno() ) // returns false if no error occurred
{
// report the error to the user, then exit program
die("Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
}
$sql="SELECT a,b,c,id FROM master_tbl ORDER BY id";
$affectedrowsno = 0;
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
$column_name = $fieldinfo->name;
// Get field information for all fields
while ($row=mysqli_fetch_assoc($result))
{
$a = $row['a'];
$b = $row['b'];
$c = $row['c'];
$id = $row['id'];
$sql = "UPDATE master_tbl SET $column_name=$a+20, $column_name=$b+50, $column_name=$c+80 WHERE id=$id";
mysqli_query($con,$sql);
$affectedrowsno += count(mysqli_affected_rows($con));
}
}
echo "Affected rows = " . $affectedrowsno;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
You can use if statement:
$column_name=$row['column_name'];//A,B,C
if (isset($result->num_rows) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$A=$row['A'];
$B=$row['B'];
$C=$row['C'];
}}
if($column_name == 'A'){
UPDATE Master SET A='$A'+20 WHERE user_id='$id'";
} elseif($column_name == 'B'){
UPDATE Master SET B ='$B'+30 WHERE user_id='$id'";
}elseif($column_name == 'C'){
UPDATE Master SET C ='$C'+50 WHERE user_id='$id'";
}
}
There are two tables in my database . TABLE 1 contains category where TABLE 2 contains category and its description .
for example
TABLE 1
id --- category
1 --- abc
2 --- eef
3 --- lmn
TABLE 2
id --- category --- description
1 --- abc --- gjhgjhdc
What I am really trying to achieve is to get 10 rows of data from each category of TABLE 1 . For example if i have 20 categories in TABLE 1, I need to fetch 10 rows from each of 20 categories from TABLE 2. I used below code and its only returns single category data, say like only from abc.
<?php
public
function getAllUserTasks($last_limt, $nxt_limt)
{
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$response["messages"] = array();
// get all category from category table
$catagory = mysql_query("SELECT cat_type FROM category") or die(mysql_error());
while ($row = mysql_fetch_array($catagory))
{
// temp user array
$cat = array();
$cat = $row["cat_type"];
// get 10 messages from each category from message table
$result = mysql_query("SELECT * FROM messages WHERE sub_category = '$cat' LIMIT 10") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0)
{
// looping through all results
// products node
while ($row = mysql_fetch_array($result))
{
// temp user array
$msgs = array();
$msgs["id"] = $row["pid"];
$msgs["language"] = $row["language"];
$msgs["category"] = $row["category"];
$msgs["sub_category"] = $row["sub_category"];
$msgs["description"] = $row["description"];
$msgs["created_at"] = $row["created_at"];
$msgs["updated_at"] = $row["updated_at"];
// push single product into final response array
array_push($response["messages"], $msgs);
}
}
else
{
// no products found
return NULL;
}
}
// success
return $response;
}
You've used the same variable - $row - for the two mysql_fetch_array calls.
Change the second one, for example, to "$messageRow = mysql_fetch_array($result)" (and then use it inside its while) and it should fix it.
I have prefixed the custom and deafaults tables of wordpress.
Also I have put data in tables but I'm getting result 0.
Connection to database is ok and working
$sql = "SELECT u_name, u_email FROM jobify_user";
$result = $conn->query($sql);
if ($result->num_rows> 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
return "id: " . $row["u_name"]. "name:".$row["u_email"]. " <br>";
}
}
else {
return "0 results";
}
$conn->close();
Considering so the prefix is "jobify" and you're using wordpress tables, and according to https://codex.wordpress.org/Database_Description#Table:_wp_users, the table_name must be jobify_users, and columns must be user_name and user_email.
So, your query must surely be :
$sql = "SELECT user_name, user_email FROM jobify_users";
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 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.