i don't know how to explain it so i will show you what i am trying to do.
mysql tables
Table Rules:
id| name|maker|model |type|price_rule
1 |client1|bmw |x5 | |24
2 |client2| | |2.0 |13
Table Products_client1:
id|maker|model |type|price
1 |bmw |x5 |2.4 |10
2 |opel |vectra|1.6 |5
3 |ford |mondeo|2.0 |15
now, i have a list of over 500k products in my mysql db, and need to update the price in the products table, with the rules from the rules table :
UPDATE products_client1,client2,... SET price=price+price_rule WHERE maker=maker or model=model or type=type
the thing is that not all clients in the Rule table have maker and model and type, some have only maker or only model or only type or a combination of the 3 and every client has a separate products table.
products_client1, products_client2.....
$sql = "SELECT * FROM Table_rule";
$Res = $conn->query ($sql) or die ("Error : " . $sql . "<br>" . $conn->error);
While($Row = $Res->fetch_assoc ()) { if (isset ($Row ["id"])) { $c_id[] = $Row ["id"]; if (isset ($Row ["name"])) { $c_name [] = $Row ["name"]; if (isset ($Row ["price_rule"])) { $c_price [] = $Row ["price_rule"]; }
$c_id_count = count($c_id);
For ($x=0; $x <> $c_id_count; $x++) { $sql_updt = "UPDATE Products_" . $c_name [$x] . " SET price=price+" . $c_price [$x] . " WHERE ";
$Conn->query ($sql_updt); }
Where what ? If this is = to this do this.....how to i check if every rule has 1...2....3....4...n maches or just 1 and hot do i apply price edit only to that item....there is always a match or more
Related
Table 1 (Which needs to be updated)
+-----------------+
|name |qty |
+-----------------+
|area | 1 |
|length | 2 |
|breadth | 3 |
|width | 4 |
+-----------------+
Table Which needs to be fetched for what values and rows have to be update
+-------------------------------------+
|name | upd_qty | Cart_id | cid |
+-------------------------------------+
|area | 6 | 12 | 1 |
|length | 8 | 20 | 2 |
|breadth | 11 | 34 | 3 |
+-------------------------------------+
How can i do this using php. Help me with this please.
this is the code i have used for my original work. Table 1 & Table 2 have name in common and conditions are
1 . UPDATE should done for the rows which are fetched from table to with where condition.
2. Table 2 upd_qty will be updated in table 1 qty while fetching data from table 2 where condition.
$con=mysqli_connect("localhost","root","","medical");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
error_reporting(E_ALL ^ E_NOTICE);
$query = "SELECT * FROM cart WHERE cid='$id' AND 'cart'='$cart_id'";
$result = $con->query($query);
while($row = $result->fetch_assoc()) {
$mediname = $row['name'];
$mediqty = $row['upd_qty'];
for($i=0;$i<$count;$i++){
$sql="UPDATE stock SET qty='$mediqty' WHERE name='$mediname' AND
'cart'='$cart_id'";
if (!mysqli_query($con,$sql))
{
die('Error: Failed' . mysqli_error($con));
}
I don't think you need this line:
for($i=0;$i<$count;$i++){
There's already a "while fetch" loop.
Also, don't use single quotes around identifiers, use backticks if the identifier needs to be escaped.
With this:
... AND 'cart' = ...
'cart' will be evaluated a string literal, not a column reference.
With this
... AND `cart` = ...
cart is an identifier, a reference to a column.
Also, if we can't use prepared statements with bind placeholders, at a minimum, we use mysqli_real_escape_string to mitigate SQL Injection vulnerabilities
Also, there's a confusing mix of procedural style and objected oriented style calls...
procedural style
mysqli_query($con,$sql)
mysqli_error($con)
object oriented style
$con->query($query)
$result->fetch_assoc()
I recommend you choose one style or the other, and stick to that pattern.
$query = "SELECT * FROM cart WHERE `cid` = '"
. $con->real_escape_string($id)
. "' AND `cart` = '"
. $con->real_escape_string($cart_id)
. "'";
$result = $con->query($query);
if( !$result ) {
die('Error: ' . $con->error());
}
while( $row = $result->fetch_assoc() ) {
$mediname = $row['name'];
$mediqty = $row['upd_qty'];
$sql="UPDATE stock SET `qty` = '"
. $con->real_escape_string($mediqty)
. "' WHERE `name` = '"
. $con->real_escape_string($mediname)
. "' AND `cart` = '"
. $con->real_escape_string($cart_id)
."'";
if(!$con->query($sql) ) {
die('Error: Failed' . $con->error());
}
}
EDIT
If there's not a specific reason for the loop, if the goal is just to perform the UPDATE operation and there is not other logic or conditions, we can do the UPDATE in one statement, without a need for multiple query executions:
UPDATE cart c
JOIN stock s
ON s.cart = c.cart
AND s.name = c.name
SET s.qty = c.upd_qty
WHERE c.cid = ?
AND c.cart = ?
Personally, I would just do the one UPDATE statement using a prepared statement
// connect to mysql
$con = new mysqli(...)
if( $con->connect_error ) {
die( 'Connect error: ' . $con->connect_error );
}
// update statement
$sql = '
UPDATE cart c
JOIN stock s
ON s.cart = c.cart
AND s.name = c.name
SET s.qty = c.upd_qty
WHERE c.cid = ?
AND c.cart = ? ';
$sth = $con->prepare($sql);
if(!$sth) {
die( 'Prepare error: ' . $con->error() );
}
$sth->bind_param('ii',$id,$cart_id);
if(!$sth->execute()) {
die( 'Execute error: ' . $con->error() );
}
Code worked for me for what i want exactly is :
$con=mysqli_connect("localhost","root","","medical");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
error_reporting(E_ALL ^ E_NOTICE);
$query = "SELECT * FROM cart WHERE cid='$id' AND cart='$cart_id'";
$result = $con->query($query);
while($row1 = $result->fetch_assoc())
foreach ($result as $row1){
$sql="UPDATE stock SET qty='$row1[upd_qty]' WHERE name='$row1[name]'";
if (!mysqli_query($con,$sql))
{
die('Error: Failed' . mysqli_error($con));
}
}
I have two tables in a database. In reports I am storing info for reports and in report_roles I am assigning which user can access the report.
reports
+--+-----------+---------------+
|id|report_name|report_filename|
+--+-----------+---------------+
|13|Report 1 |reportname1 |
|14|Report 2 |reportname2 |
|15|Report 3 |reportname3 |
+--+-----------+---------------+
report_roles
+---------+-------+
|report_id|user_id|
+---------+-------+
|14 |1 |
|13 |1 |
|14 |2 |
|13 |2 |
+---------+-------+
I want to display all the reports from table reports with checkboxes and check only those which are added in the report_roles associated with the user id. This is the code I am running:
$id = $_POST['user_id'];
$query = "SELECT * FROM reports LEFT JOIN report_roles ON report_roles.report_id = reports.id";
$sql = mysqli_query($mysqli, $query);
if (!$sql) {
printf("Error: %s\n", mysqli_error($mysqli));
exit();
}
while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC) ) {
if ($row['user_id'] == $id) {
echo "<input type='checkbox' name='" . ($row['id']) . "'" . "id='" . ($row['id']) . "'" . "value='yes'" . ($row['user_id'] == $id ? 'checked' : '') .">";
echo $row['report_name'];
} else {
echo "<input type='checkbox' name='" . ($row['id']) . "'" . "id='" . ($row['id']) . "'" . "value='yes'" . ">";
echo $row['report_name'];
}
}
If $id = 1 I am receiving this:
|checked| Report2 |checked| Report 1 |unchecked| Report2 |unchecked| Report 1 |unchecked| Report3
Which is completely right based on the code I wrote. I cannot figure out how to display all the reports without duplicates from reports table and check only those which are available in report_roles, something like this:
|checked| Report2 |checked| Report 1 |unchecked| Report3
I am sure I have to change my query with the join. Tried to do accomplish this task with two separate queries without joins but with no luck. Hope someone can help.
Actually I was just missing a statement in my query and thanks to Bernd Buffed I realized that I have to add one AND at the end of the query and it should look like this:
$query = "SELECT * FROM reports LEFT JOIN report_roles ON report_roles.report_id = reports.id AND user_id = $id";
Till now I was adding WHERE user_id = $id and was receiving only those reports which exists in report_roles. With the AND I am receiving all reports from reports table and my script can check only those which are in report_roles based on a simple php check.
I am inserting values into a MySQL table using the code below, and I need to prevent users from inserting the same priority value for each studentname more than once. What is the best way to do this please?
This is the table:
id studentname title academicdiscipline priority
012345678 TEST, NAME Test title 1 Civil 1
012345678 TEST, NAME Test title 2 Civil 2
012345678 TEST, NAME Test title 3 Civil 3
012345678 TEST, NAME Test title 4 Civil 4
012345678 TEST, NAME Test title 5 Civil 5
Code:
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
$ids = $_POST['id'];
$names = $_POST['studentname'];
$titles = $_POST['title'];
$disciplines = $_POST['academicdiscipline'];
$priorities = $_POST['priority'];
foreach($priorities as $key => $priority) {
if ($priority > 0) {
$query = "INSERT INTO flux_project_selection (id, studentname, title, academicdiscipline, priority)
VALUES ( " . mysql_real_escape_string($ids[$key]) . ",
'" . mysql_real_escape_string($names[$key]) . "',
'" . mysql_real_escape_string($titles[$key]) . "',
'" . mysql_real_escape_string($disciplines[$key]) . "',
" . mysql_real_escape_string($priority) . " )";
$retval = mysql_query($query) or die(mysql_error());
}
}
echo "<p> Added.</p><br />";
}
Create index for unique record, using combination of fields
ALTER TABLE table_name ADD UNIQUE INDEX index_name (field1, field2);
it will allow you to add first record but on duplicate entry show Duplicate entry ... for unique index. You can either use try and catch to display error message or use on duplicate update record if your project has this requirement.
query for the max priority for the student then increment it with 1.
$queryMaxPriority = 'select max(priority) from flux_project_selection where id = STUDENT_ID;
$priority_no = $queryMaxPriority + 1;
i used this in some of my apps i developed.
Update
$priority = 'select count(priority) from flux_project_selection where id = STUDENT_ID and priority = PRIORITY';
if (count($priority>0)){
//send some error message in your page.
}
i fetch id and name from categories table like this :
|id|name| tag |desc|order|status|
|1 |test| NULL|NULL| 1 | 1 |
$i = 0;
$allcats = Access::FETCH("SELECT * FROM " . CATS . "");
$cats = array();
foreach($allcats AS $row2){
$cats[$i] = array("name" => $row2['name'], "id" => $row2['id']);
$i++;
}
i fetch category id for each news :
|id|catid|storyid|
|1 | 1 | 5 |
$groupcats = Access::FETCH("SELECT * FROM " . GROUPCATS . " WHERE storyid = ?", $row['postid']);
Now, i need to print name of cat for storyid. i,e : i need to print test(catname) for story id 5.
How do can i print this?
Easier to do with with a join rather than in php. Something like,
$joinedcats = Access::FETCH("SELECT name FROM " . CATS .
" JOIN " . GROUPCATS . " ON catid = id");
foreach($joinedcats as $row) {
echo $row['name'];
}
See https://dev.mysql.com/doc/refman/5.5/en/join.html
You can use join to get needed rows for each story:
"SELECT * FROM " . GROUPCATS . " LEFT JOIN " . CATS . " USING(categoryid) WHERE storyid = ?"
I have this table,
--------------------------------------------
| products_id | related_products_ids |
| -----------------------------------------
| 1 | 1,2,3,4,6, |
| -----------------------------------------
| 2 | 1,2,3, |
| -----------------------------------------
| 3 | 1,2, |
-------------------------------------------
I want to display those related products in the product page. How can I do that?
Example, I'm in the product page where products_id is 1, i want to display the products from a table like table_name1 by related_products_ids.
I have used this code for displaying data,
$sql = "SELECT related_products_ids FROM ".TABLE_RELATED_PRODUCTS." where products_id = '" . (int)$_GET["products_id"]."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$lst_rp = explode(',', $row['related_products_ids']);
echo '<ul>';
foreach($lst_rp as $rp_id) {
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
$result1 = mysql_query($res);
$row1 = mysql_fetch_array($result1);
echo '<li>'.$row1['products_name'].'</li>';
}
echo '</ul>';
However, it displays nothing.. Is there something wrong with my code? Do you have any solution for this?
Thank you.
You have placed the actual database query section outside of the loop.
You should include this within the foreach loop, so that every time, a new query runs and you will receive the results as you anticipated.
foreach($lst_rp as $rp_id) {
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
$result1 = mysql_query($res);
while($row1 = mysql_fetch_array($result1)) {
echo $row1['products_name'];
}
}
And one more thing, since you are using double quotes to wrap your query, you can shorten it two
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='$rp_id'";
Update
Use the following code to ensure the <li> is not empty
foreach($lst_rp as $rp_id) {
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
$result1 = mysql_query($res);
$row1 = mysql_fetch_array($result1);
echo !empty($row1['products_name']) ? '<li>'.$row1['products_name'].'</li>' : '';
}
Please try with this
$sql = "SELECT related_products_ids FROM ".TABLE_RELATED_PRODUCTS." where products_id = '" . (int)$_GET["products_id"]."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$lst_rp = explode(',', $row['related_products_ids']);
foreach($lst_rp as $rp_id) {
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
$result1 = mysql_query($res);
$row1 = mysql_fetch_array($result1);
echo $row1['products_name'];
}
In your code
$lst_rp = explode(',', $row['related_products_ids']);
gives you an array of related product ids which is fine. But then in your loop:
foreach($lst_rp as $rp_id) {
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
}
you are overwriting the value of $res in each loop iteration so when you do the next query
$result1 = mysql_query($res);
it will only fetch the last related product id from the database.
please change only
$row1=mysql_fetch_assoc($result1);
i means
foreach($lst_rp as $rp_id) {
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
$result1 = mysql_query($res);
$row1 = mysql_fetch_assoc($result1);
echo $row1['products_name'];
}