for ($i = 0; $i < count($cart); $i++) {
$proid = $cart[$i]["proid"]; //1
$prodName = $cart[$i]["prod_name"]; //2
$price = $cart[$i]["unit_price"]; //3
$taken = $cart[$i]["taken"]; //4
if ($cart[$i]['taken'] > 0) {
$sql = "INSERT INTO `tblchitiethoadon`(`Ma_HD`, `Ma_SP`, `Ten_SP`, `SoLuong`, `Gia`)";
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price})";
$result = mysql_query($sql);
/* $mahd i got it before */
}
}
I got 3 elements in array $cart,2 of them got cart[$i]['taken'] > 0 (i also echo $cart with $cart[$i]['taken'] > 0 condition for sure ) but in the database i just got the first and only one element.
Typo/Syntax Error
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price})";
----------------------------------------------------------------------------------------------------------^(semicolon missing)
correct:
$sql.=" VALUES ({$mahd},{$proid},'{$prodName}',{$taken},{$price});";
-----------------------------------------------------------------------------------------------------------^
Reason:
Since you are using for loop to form the query.your query will look like
insert into table1(a,b,c) values(1,1,1)insert into table1(a,b,c) values(2,3,4)
which is wrong syntactically.
see here
you can echo your $sql and run it in phpmyadmin
Better Approach:
The better approach to your code(it will reduce the unwanted overhead,form the string inside the loop and execute it outside the loop):
$sql1 = "INSERT INTO `tblchitiethoadon`
(`Ma_HD`, `Ma_SP`, `Ten_SP`, `SoLuong`, `Gia`) VALUES";
for ($i = 0; $i < count($cart); $i++) {
$proid = $cart[$i]["proid"]; //1
$prodName = $cart[$i]["prod_name"]; //2
$price = $cart[$i]["unit_price"]; //3
$taken = $cart[$i]["taken"]; //4
if ($cart[$i]['taken'] > 0) {
$sql11.=" ({$mahd},{$proid},'{$prodName}',{$taken},{$price}),";
}
}
$sql=$sql1.$sql11;
$sql=trim($sql,",");//to remove the extra semicolon at the end of the string.
$result = mysql_query($sql);
Please Dont use mysql_* as these are depracated and you are prone to sql injections.
Loop will execute count($cart) times and the insertion action will occure if ($cart[$i]['taken'] > 0) is true.Make sure the condition is true for each time.
Try these this coding:
$sql = "INSERT INTO tblchitiethoadon (Ma_HD, Ma_SP, Ten_SP, SoLuong, Gia) VALUES ('$mahd','$proid','$prodName','$taken','$price')";
$result = mysql_query($sql);
Related
I have 2 queries.
and 2 while loops.
my problem is that When I call out the values. only one query and one loop is correct. the other loop is displaying duplicate values.
here is what I have :
$query1=mysql_query("SELECT * FROM table1");
$query2=mysql_query("SELECT * FROM table2");
while($row1=mysql_fetch_array($query1)){
while($row2=mysql_fetch_array($query2)){
echo $row1['nameofattribute'] ;
echo $row2['nameofattribute'] ;
}
}
the output of query 1 is correct. but the output of query 2 is duplicate values.
for example :
query 1= $row1=2 $row1=3 $row1=4
query 2= $row2=3 $row2=3 $row2=3
instead it should be
query 1= $row1=2 $row1=3 $row1=4
query 2= $row2=1 $row2=2 $row2=3
on top is my simple translation of the code. here is my real code :
$query1 = mysql_query("SELECT remarks FROM passed_deliverable WHERE user_id=$uid && deliverable_category_id=4");
$query2=mysql_query("SELECT
deliverable_id, deliverable_title, deliverable_desc, adviser_id ,deliverable_category_id
FROM deliverable d
WHERE d.deliverable_category_id=4
&& EXISTS (
SELECT 'X'
FROM passed_deliverable pd
WHERE pd.deliverable_id = d.deliverable_id && user_id='".$_GET['edit']."' && adviser_id='".$_SESSION['user_id']."' ) ");
while($x=mysql_fetch_array($query1)){
while($deliverable=mysql_fetch_assoc($query2)){
echo "
{$deliverable['deliverable_desc']}
{$x['remarks']}
";
try this :
other answer or loop from mr. hellcode
it shows that you can also use array values instead of just using array
$a1 = 0[];
$a2 = 0[];
while($x=mysql_fetch_array($query1)) {
$a1[] = $x['remarks'];
}
while($deliverable=mysql_fetch_assoc($query2)) {
$a2[] = $deliverable['deliverable_desc'];
}
for($i=0; $i < count($a1) and $i < count($a2); $i++) {
echo "\n\n".$a2[$i]."\n".$a1[$i];
}
Assuming that you just want to combine the resulting rows of both tables in their appearing order (ignoring results that exceed the other table):
$a1 = array();
$a2 = array();
while($x=mysql_fetch_array($query1)) {
$a1[] = $x['remarks'];
}
while($deliverable=mysql_fetch_assoc($query2)) {
$a2[] = $deliverable['deliverable_desc'];
}
for($i=0; $i < count($a1) and $i < count($a2); $i++) {
echo "\n\n".$a2[$i]."\n".$a1[$i];
}
Deprecation of mysql_ functions . Please avoid mysql_ function . Anyway your query seems to unusual. because we don't see any WHERE clause in your queries . That means it will return duplicate value. Table1 each row will be check all rows of Table2 .
CODE :
$nerd_result = mysql_query("select * from nerd_profile where nerd_reg_no = '$reg_no'");
$nerd_data = mysql_fetch_array($nerd_result);
$tags = array();
$tags = explode(",",$nerd_data['nerd_interests']);
for($i = 0; $i < sizeof($tags)-1; $i++)
{
if($i != sizeof($tags)-2)
{
$sub_query = $sub_query."`tags` like %".$tags[$i]."% or ";
}
else
{
$sub_query = $sub_query."`tags` like %".$tags[$i]."% ";
}
}
$proper_query = "select * from `qas_posts` where ".$sub_query." and `post_date` like '%$today%'";
$result = mysql_query($proper_query);
while($each_qas = mysql_fetch_array($result))
Description :
I am adding the like clause along with php variable in a string and concatenating it with the further variables with like clause to come. In the end when I echo I get the perfect query that I want but
mysql_fetch_array()
does not accept that generated query rather if I hard code it , it works perfect what am I doing wrong ?? can I do that ??
When doing string comparisons in mysql you need to make sure you have quotes around your comparison value.
$sub_query = $sub_query."`tags` like '%".$tags[$i]."%' or ";
and
$sub_query = $sub_query."`tags` like '%".$tags[$i]."%' ";
I have a set of rows with five fields. My requirement is if "Internal_Deadline" field is greater than "Client_Deadline" in any of the rows, then it has to display a alert saying "Internal Deadline should not be greater than Client Deadline". Now it's checking only with the first row. I need to check with all the rows. Thanks
<?php
for( $i = 1; $i <= 100; $i++ )
{
$task = $_POST['task'.$i];
$Description = $_POST['Description'.$i];
$Internal_Deadline = $_POST['Internal_Deadline'.$i];
$Client_Deadline = $_POST['Client_Deadline'.$i];
$Actual_Deadline = $_POST['Actual_Deadline'.$i];
if(strtotime($Internal_Deadline) > strtotime($Client_Deadline)){
?>
<script>alert('Internal Deadline should not be greater than Client Deadline');</script>
<?php
}
else{
$result_task=mysql_query("select * from project_plan where p_id='$p_id' and task_no='$i'", $dbconnect1);
$row_task=mysql_fetch_array($result_task);
$id=$row_task['id'];
if(mysql_num_rows($result_task)!=0){
$update_result=mysql_query("update project_plan set Task='$task',Description='$Description',Internal_Deadline='$Internal_Deadline',Client_Deadline='$Client_Deadline',Actual_Deadline='$Actual_Deadline' where id='$id'", $dbconnect1);
}
else{
if($task!=""){
$que = mysql_query("insert INTO project_plan(task_no,Task,Description,Internal_Deadline,Client_Deadline,Actual_Deadline,Created_Date,p_id) VALUES ('".$i."','".$task."','".$Description."','".$Internal_Deadline."','".$Client_Deadline."','".$Actual_Deadline."','".$current_date."','".$p_id."')", $dbconnect1);
}
}
}
}
First of all the length of your for loop is not correct.
You need to run this loop exact same times to the post data count.
secondly i have tried locally with your given data(in your comment). it seems that is not met the condition:
if(strtotime($Internal_Deadline) > strtotime($Client_Deadline)){
try like this:
it will skip unnecessary loops. if you have task1,task2,task3 set in post data then it will run for 3 times not 100 times as your implementation.
$i=1;
while(isset($_POST['task'.$i]))
{
$task = $_POST['task'.$i];
$Description = $_POST['Description'.$i];
$Internal_Deadline = $_POST['Internal_Deadline'.$i];
$Client_Deadline = $_POST['Client_Deadline'.$i];
$Actual_Deadline = $_POST['Actual_Deadline'.$i];
if(strtotime($Internal_Deadline) > strtotime($Client_Deadline)){
?>
<script>alert('Internal Deadline should not be greater than Client Deadline');</script>
<?php
}
else{
$result_task=mysql_query("select * from project_plan where p_id='$p_id' and task_no='$i'", $dbconnect1);
$row_task=mysql_fetch_array($result_task);
$id=$row_task['id'];
if(mysql_num_rows($result_task)!=0){
$update_result=mysql_query("update project_plan set Task='$task',Description='$Description',Internal_Deadline='$Internal_Deadline',Client_Deadline='$Client_Deadline',Actual_Deadline='$Actual_Deadline' where id='$id'", $dbconnect1);
}
else{
if($task!=""){
$que = mysql_query("insert INTO project_plan(task_no,Task,Description,Internal_Deadline,Client_Deadline,Actual_Deadline,Created_Date,p_id) VALUES ('".$i."','".$task."','".$Description."','".$Internal_Deadline."','".$Client_Deadline."','".$Actual_Deadline."','".$current_date."','".$p_id."')", $dbconnect1);
}
}
}
$i =$i +1;
}
<?php
$query = $_GET['query'];
// gets value sent over search form
$min_length = 6;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM cwnational WHERE (`postcode` = '$query') OR (`structure` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
echo "<p><h3>".$results['postcode']."</h3>".$results['structure']."</p>";
}
while($results = mysql_fetch_array($raw_results)){
if($results['structure'] = "National") {
echo "print national_table";
} else {
echo "print local_table";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
</body>
I'm totally stumped now..
When I successfully match a $query, I want to use the 2nd part of the array which should be a column called structure and use that as a switch to either print table_local or table_national from the db.
re-wrote it after getting to grips with the correct approach,
if (empty($searchTerm)) {
echo "<h1>Empty search term</h1>";
$sqlQuery = false;
} elseif (strlen($searchTerm) < $minQueryLength) {
echo "<h1>Search term must be at least ".$minQueryLength." characters long.";
$sqlQuery = false;
} else {
if (strlen($firstPart) + strlen($secondPart) == 7) {
$sqlQuery = $mysqli->query("SELECT `postcode`, `structure` FROM `cwnational` WHERE `postcode` LIKE '".$firstPart." ".$secondPart."'");
} else {
$sqlQuery = $mysqli->query("SELECT `postcode`, `structure` FROM `cwnational` WHERE REPLACE(`postcode`, ' ', '') LIKE '".$searchTerm."%'");
}
}
if (is_object($sqlQuery) && $sqlQuery->num_rows >= 1) {
$resultArr = array();
while($row = $sqlQuery->fetch_assoc()) {
$resultArr[$row['postcode']] = array();
$priceQuery = $mysqli->query("SELECT `base_rate`, `commit_mbps` FROM `pricing` WHERE `structure` = '".$row['structure']."'");
if ($priceQuery->num_rows >= 1) {
while ($price = $priceQuery->fetch_assoc()) {
$resultArr[$row['postcode']][$price['commit_mbps']] = ((float)$price['base_rate'] + $transit[$price['commit_mbps']] ) + ( ( $transit[$price['commit_mbps']] + (float)$price['base_rate'] ) * ((float)$apiUser['margin']/100) ) ;
}
}
}
You're reading the result set twice. This will work for the first loop, but won't execute the second because you've already reached the end. If you need to read the results twice, use this:
mysql_data_seek ($raw_results , 0 )
immediately before the second loop to set the pointer to the beginning again.
Of course, you should be using mysqli...
what's going wrong now? I see you need to add an equals sign here:
if($results['structure'] == "National") {
note: double equals for php conditional
It also looks like you have an "else" coming out of a "while", that won't work. And you did this "while" loop twice, I'd combine them into a single "While":
while($results = mysql_fetch_array($raw_results)){
Need a little help, advise, or link to an example or useful tutorial so I can learn this. As I am very new to programming in general.
I have 11 Select boxes in a form named 'ore1' thru 'ore11' that send data up to $_POST.
This little block turns that into an array that is used in another function.
//function calculateValue($sellValue){ -- add when you figure it out
if(isset($_POST['submit'])){
$i = 11 //total number of select boxes
$pdquery = "SELECT * FROM ore
WHERE '".$_POST['ore1']."'
LIKE id";
$result = mysql_query($pdquery);
$oredata1 = array();
while ($row = mysql_fetch_row($result)) {
$oredata1 = $row; }
}
else {}
}
I'd like like to be able to use this one bit of code with all 11 Select boxes without having to copy it 11 times by getting
.$_POST['ore#']. //5th line
$oredata# = $row; //10th line
to replace # with the appropriate # depending on the select box it is used on.
Any tips?? Thanks in advance.
In your HTML:
<select name="ore[]">
...
</select>
<select name="ore[]">
...
</select>
In your PHP
if(isset($_POST['submit']) && isset($_POST['ore'])){
foreach($_POST['ore'] as $ore){
$ore = (int)$ore;
$pdquery = "SELECT * FROM ore WHERE id = $ore";
...
}
}
Also do not use mysql_* function since deprecation process has begun
for ($i = 1; $i <= 11; $i++) {
$ore = 'ore'.$i;
$pdquery = "SELECT * FROM ore WHERE '".$_POST[$ore]."' like id";
...
execute it in a for-loop - from 1 to 11. Then you can use the variable $i to access stuff.
// I assume that there is some MySQLi object called $mysqli already present. You'll have to create it if it does not
if(isset($_POST['submit'])){
$pdquery = 'SELECT * FROM ore WHERE id LIKE ?';
$oredata = array();
if($stmt = $mysqli->prepare($pdquery)) {
for($i = 1; $i < 12; $i++) {
$ore = 'ore' . $i;
if(empty($_POST[$ore])) {
continue;
}
$oreValue = (int)$_POST[$ore];
$stmt->bind_Param('i', $oreValue);
$stmt->execute();
$oredata[$i] = $stmt->get_result()->fetch_array(MYSQLI_ASSOC);
}
}
$stmt->close();
}
This does NOT take into consideration the fact that there might be more than just those eleven inputs. Using an array on HTML side would certainly be cleaner (And you'd just have to replace the for-loop with a foreach-loop and use the key instead of $ore)