PHP - Conditional Insert Where Clause Issue
Hi,
I've been playing around with inserting the name of a file ($additional_upload_nameX) into the database only if it has been uploaded (it's not mandatory). When I submit the form, I'm told I have a problem with my WHERE clause. Any idea what I'm doing wrong here? Code: [Select] $query2 = "INSERT INTO uploads (date, upload_name, topic, year, status, keywords, description )" . "VALUES (NOW(), '$additional_upload_nameX', '$topic', '$year', '$status', '$keywords' , '$description') WHERE $additional_upload_nameX != ''"; //if($query){echo 'data has been placed'} mysql_query($query2) or die(mysql_error()); Similar TutorialsI have a php script that I've been running that seems to have been working but now I'm wondering if some of my logic is potentially off. I select records from a db table within a date range which I put into an array called ```$validCount``` If that array is not empty, that means I have valid records to update with my values, and if it's empty I just insert. The trick with the insert is that if the ```STORES``` is less than the ```Quantity``` then it only inserts as many as the ```STORES``` otherwise it inserts as many as ```Quantity```. So if a record being inserted with had Stores: 14 Quantity:12
Then it would only insert 12 records but if it had It would only insert 1 record. In short, for each customer I should only ever have as many valid records (within a valid date range) as they have stores. If they have 20 stores, I can have 1 or 2 records but should never have 30. It seems like updating works fine but I'm not sure if it's updating the proper records, though it seems like in some instances it's just inserting too many and not accounting for past updated records. This is the logic I have been working with:
if(!empty($validCount)){ for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $out[] = $failedUpdate; } } }else{ if($row2["QUANTITY"] >= $row2["STORES"]){ for($i=0; $i<$row2["STORES"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertStore; } } }elseif($row2["QUANTITY"] < $row2["STORES"]){ for($i=0; $i<$row2["QUANTITY"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertQuantity; } } } }
Let's say customer 123 bought 4 of product A and they have 10 locations
customerNumber | product | category | startDate | expireDate | stores Because they purchased less than their store count, I insert 4 records. Now if my ```$validCheck``` query selects all 4 of those records (since they fall in a valid date range) and my loop sees that the array isn't empty, it knows it needs to update those or insert. Let's say they bought 15 this time. Then I would need to insert 6 records, and then update the expiration date of the other 9 records.
customerNumber | product | category | startDate | expireDate | stores There can only ever be a maximum of 10 (store count) records for that customer and product within the valid date range. As soon as the row count for that customer/product reaches the equivalent of stores, it needs to now go through and update equal to the quantity so now I'm running this but it's not running and no errors, but it just returns back to the command line $total = $row2['QUANTITY'] + $validCheck; if ($total < $row2['STORES']) { $insert_count = $row2['QUANTITY']; $update_count = 0; } else { $insert_count = $row2['STORES'] - $validCheck; // insert enough to fill all stores $update_count = ($total - $insert_count); // update remainder } for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $failedUpdate = "UPDATE_FAILED"; print_r($failedUpdate); $out[] = $failedUpdate; } } for($i=0; $i<$insert_count; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $failedInsertStore = "INSERT_STORE_FAILED!!!: " . $ex->getMessage(); print_r($failedInsertStore); $out[] = $failedInsertStore; } }```
Hello, this is my first PHP project, and I am having issues getting it to correctly display an error ONLY if the input is an error It displays the error upon first load of the page w/o pressing submit. How would I use Code: [Select] isset($_POST['submit'])to fix it? Code: [Select] <?php $inputid = $_POST['steamid']; $steam_prefix = substr($inputid, 0, 10); $prefix_length = 10; $char_total = strlen($inputid); $steam_suffixchars = ($char_total - $prefix_length); $suffix_check = substr($inputid, 10, $steam_suffixchars); $class_set = "notranslate"; $is_submit = isset($_POST['submit']); if(is_numeric($suffix_check) == true) $suffix_valid = true; elseif(is_int($suffix_check) == false) $suffix_valid = false; if($char_total > 25 || $char_total < 11) $char_valid = false; else $char_valid = true; if($steam_prefix === "STEAM_0:1:" || $steam_prefix === "STEAM_0:0:") $prefix_check = true; elseif($steam_prefix != "STEAM_0:1:" || $steam_prefix != "STEAM_0:0:") $prefix_check = false; if (preg_match('/^[A-Z0-9-:-_-]+$/', $inputid)) $chars_matched = true; else $chars_matched = false; if($suffix_check == true && $prefix_check == true && $char_valid == true && $chars_matched == true) echo "Approved!"; elseif(isset($_POST['anon'])) echo "Approved!"; else echo "error!"; ?> Hello everyone, I am trying to write a client database in php & mysql, Its going to be a localized system not online, just run through a home server. really simple stuff not much security, etc. For some reason it does not want to insert into the database, keeps giving me different errors, at first i tried the account# as '' and it told me to check my version of mysql for proper syntax, i am using version 5.1.13, but then i tried $_POST, and im getting a parse error, i'm lost here, dont understand why its not matching up, everything is spelled right. basically i have a customer information table with the fields, account_# {primary key, auto increment}, name_first, name_last, address, city, state, zipcode, telephone, telephone_alt here is my web form code "very very rough draft, just started trying to make it work before it looks pretty lol" Code: [Select] <form action="add_customer.php" method="post"> Account#: <input type="text" name="account_#" /> Firstname: <input type="text" name="name_first" /> Lastname: <input type="text" name="name_last" /> Address: <input type="text" name="address" /> City: <input type="text" name="city" /> State: <input type="text" name="state" /> Zipcode: <input type="text" name="zipcode" /> Telephone: <input type="text" name="telephone" /> Telephone Alt: <input type="text" name="telephone_alt" /> <input type="submit" /> </form> then add_customer.php is Code: [Select] mysql_select_db("terra_elegante_operations", $con); $sql="INSERT INTO customer_information (account_#, name_first, name_last, address, city, state, zipcode, telephone, telephone_alt) VALUES ('$_POST[account_#]','$_POST[name_first]','$_POST[name_last]','$_POST[address]','$_POST[address]','$_POST[city]','$_POST[state]','$_POST[zipcode]','$_POST[telephone]','$_POST[telephone_alt]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; Hi,
I'm currently passing an array of values to be updated in my database, but am struggling on the best way to escape the quotation marks around the NOW statement below, as understand this will only work without them. This is what is being passed to the DB which does not currently work. I'm seeking some help to find the best way to remove the "" from around the NOW statement, but retain it in the array structure which i believe needs the '' to understand its a value. UPDATE staff SET staff_last_login="NOW()" WHERE staff_id="1" array('staff_last_login'=>'NOW()')My question is - whats the best way to escape this? I understand forward slashes can sometimes be used, and double quotes - but feel like i have exhausted all my known options. Any help much appreciated. MoFish In drive.php
public function insert($postBody, $optParams = array()) Hi. I am building an update table form. In this table there are only two fields, Header and Intro. Now I have the form and currently it displays whats already in the database. Now when the user edits these two fields and presses edit. Obviously I want it to update these fields. I have the code here but there is an issue with it. At the end of the update I believe I need a update fields WHERE....... which would be used if there was more than one entrance in the table but there is and only ever will be one entry. WHERE what? I dont have a where anything. Do I need this or can it be omitted somehow? <?php if(isset($_POST['edit'])){ //Process data for validation $header = trim($_POST['header']); $intro = trim($_POST['intro']); //Perform validations next //Prepare data for db insertion $header = mysql_real_escape_string($header); $intro = mysql_real_escape_string($intro); //insert $qUpdateDetails = "UPDATE index SET `header` = '".$header."', `intro` = '".$intro."', WHERE ???????='".?????????."'"; $rUpdateDetails = mysql_query($qUpdateDetails) or die(mysql_error()); //next page $page_edit = "Index page has been edited"; $url = "signed.php?edit='".$page_edit."'" or die(mysql_error()); header("Location: ".$url."") or die(mysql_error()); exit(); } } ?> Hi
I am now on to viewing listings but want to to show listings that are just submitted by that user and display them on their profile page but can't get the WHERE clause working
Below is the coding for what I have
Profile page
echo "<p><a href='view-private-listings.php?id={$_SESSION['user_id']}'>View Listings</a></p>";Add Listing page HTML Submitted By: <input type="text" name="submittedby">View Listings Page <?php ini_set('display_startup_errors',1); ini_set('display_errors',1); error_reporting(-1); ?> <?php $title = "Private Seller Listings"; include ( 'includes/header.php' ); ?> <?php require_once("functions.php"); $con=mysqli_connect("host","username","password","database"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // Start a session for error reporting session_start(); $submittedby=$_POST['submittedby']; $listingtitle=$_POST['listingtitle']; $query = mysqli_query($con,"SELECT listingtitle FROM privatelistings WHERE item LIKE '%$submittedby%'"); echo "<p>Title: {$listingtitle['listingtitle']}</p>"; mysqli_close($con); ?> <?php include( 'includes/footer.php' ); ?>All I get is the following error Notice: Undefined index: listingtitle in /zacs-car-site/view-private-listings.php on line 26 Thank you in advance Kind regards Ian hi, how can I add more than one ID to a WHERE clause? Code: [Select] "SELECT * FROM t_mytable WHERE id_product = 1 "; I need to select products with different id's i.e Code: [Select] "SELECT * FROM t_mytable WHERE id_product = 1,2,3,4,5 "; Thanks This may be super simple, but it's stumping me. Is this an If/Then clause: Code: [Select] ($month != 1 ? $month - 1 : 12) Is it saying if $month does not equal 1 then $month-1; if so, then what does the colon mean? If not, then what is this piece of code doing? Code: [Select] $search = "`title` LIKE '%Silvin AND wts%'"; I want to search for both of those keywords why not work? Hi, I have a SQL statement: $sql='SELECT PROPID, ADDRESS_1, ADDRESS_2, TOWN, POSTCODE1, POSTCODE2, BEDROOMS, BATHROOMS, RECEPTIONS, PRICE, TRANS_TYPE_ID FROM properties WHERE TRANS_TYPE_ID=2 AND BEDROOMS =3 AND PROP_SUB_ID IN (1,2,3,4,5,6,21,22,23,24,27,30,95,128,131) ORDER BY DATE_ADDED, PROPID DESC'; I want to be able to get the fields and their corresponding values as such: $result['TRANS_TYPE_ID']=2; $result['BEDROOMS']=3; And then capture the values in PROB_SUB_IN IN(*) How can I do this? Any help will be greatly appreciated. Thanks Hi, I have an empty array and i populated the array through code and i printed to check if everything ok. So far so good. I now have an array say $ids = ('123','456'). Now, i have a table in db that has ids as well, I need to make a query to check for id's that are not inside the array, so if the db table have '123','456','789' i want the result of the query to be only the last one '789'. $arr = array(); array_push($arr,$previd2); print_r ($arr); I get the result as follows: Array ( [0] => 533349 [1] => 533355 ) so what query i can use to get the other id's from db table that is not part of that array? here is what i tried: $qry = "select staffname, joindate from staff WHERE OracleID NOT IN ($arr)"; $answ = mysqli_query($con, $qry); I get error: Notice : Array to string conversion in C:\xampp\htdocs\AttendanceSystem\login\reportsforallid.php Edited March 30, 2020 by ramiwahdan more info I am brand new to mysql and php but I have created a database and loaded two tables using cPanel and phpMyAdmin. Now I need some programs to access my data. I have a couple of simple ones that work, but I can't figure out what I really need, I am trying to Select a table Where the Value is a $variable, not a fixed value. Of course the end result will be to pass the value from a Form, but I have to get this to work first. <?php // Connect to database============================= include("connect_db.php"); $table='airplanes'; $amano='123456' $iden='1' // Send query =========================================================== // $result = mysql_query("SELECT * FROM {$table} where ama='123456'"); == this works // $result = mysql_query("SELECT * FROM {$table} where ama='940276'"); == this works // $result = mysql_query("SELECT * FROM {$table} where id='1'"); // this works // $result = mysql_query("SELECT * FROM {$table} where id = '{$iden}'"); == doesnt work // $result = mysql_query("SELECT * FROM {$table} where id = $iden"); == doesnt work // $result = mysql_query("SELECT * FROM {$table} where id = ($iden)"); // == doesnt work // $result = mysql_query("SELECT * FROM {$table} where id = $iden"); // == doesnt work // $result = mysql_query("SELECT * FROM {$table} where ama='$amano'"); // == doesnt work $result = mysql_query("SELECT * FROM {$table} where ama=($amano)"); // == doesnt work Thanks Hey guys, I don't know what to do. I've got a script used for gamble: $gamble_rand = rand($number_of_tickets,$gamble_chance); if($gamble_chance == $gamble_rand){ If $number_of_tickets is set by 99 and $gamble_chance is set by 100 the chance is 1:100 that the If-Clause is not true. But it seems to me that PHP is making its on "random". Independent of the values PHP is interpreting that 20 times of 100 times the correct logic is false... If $number_of_tickets is set by 1 there's no big different. Its just a little bit less, but not the chance that it has to be. Thanks for helping and Merry Christmas :-) This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=330779.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=350684.0 hello. i have a column called "pageName" and on the each page i have put $pName = "the name of that page". i want to pull from the database all the information where the $pName on the page is the same as the pageName in the database its getting the $pName = "adminHome" but it thinks its the name of the column not the row. this is the error im getting: Quote DATABASE.PHP - confirm_query = MySQL Datatbase Query Failed: Unknown column 'adminHome' in 'where clause' Last SQL query: SELECT * FROM pages WHERE pageName=adminHome this is the function code Code: [Select] public static function find_by_pageName($pName=""){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE pageName=".$database->escape_value($pName).""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } this is the page code Code: [Select] <?PHP require_once("../includes/initialize.php"); $pName = "adminHome"; $page = Pages::find_by_pageName($pName); ?> thanks rick I have this code: Code: [Select] if (isset($_POST['update'])){ $ids = implode(",", array_map('intval', $_POST['m'])); $ranks = implode(",", array_map('intval', $_POST['ranks'])); if ($ids < 1) message("Incorrect Data"); if ($ranks < 0) message("Incorrect Data"); echo $ids; echo "<br>"; echo $ranks; exit; $db->query('UPDATE friends set RANKS WHERE friend_id IN ('.$db->escape($ids).') AND user_id = '.$pun_user['id'].'') or error('Unable to remove users from online list', __FILE__, __LINE__, $db->error()); redirect("s.php?section=Friends","Thanks, Ranks Updated"); } I grab the id's from the rank This will spit out 3,4 for $ids and for $ranks, 1,2 as you can see, set for 1 and 2 respectivaly. My problem is how can I use MYSQL to update the data correspond to each id using a IN clause? Code: [Select] $db->query('UPDATE friends set RANKS = "LOST $RANKS? HERE" WHERE friend_id IN ('.$db->escape($ids).') AND user_id = '.$pun_user['id'].'') or error('Unable to remove users from online list', __FILE__, __LINE__, $db->error()); Hi,
Im having a problem and I can't seem to figure it out or find anything on the net.
If I use the following code the script successfully updates every row in the table:
mysqli_query($con,"UPDATE Ads SET Ads_LocalArea='Stroud'");However if I try updating the table using the WHERE clause in any of the combinations below nothing happens. mysqli_query($con,"UPDATE Ads SET Ads_LocalArea='Stroud' WHERE Ads_ID=$DBROWID");---------------------------------------------------------------------- My Script: mysqli_query($con,"INSERT INTO Ads (Ads_ID, Ads_AID, Ads_Title) VALUES ('', '$Polished_AdRef', '$Polished_AdTitle')"); $DBROWID = mysqli_insert_id($con); mysqli_query($con,"UPDATE Ads SET Ads_AID='Stroud' WHERE Ads_ID=$DBROWID"); // TRIED THESE TOO // mysqli_query($con,"UPDATE Ads SET Ads_AID='Stroud' WHERE Ads_ID='$DBROWID'"); // mysqli_query($con,"UPDATE Ads SET Ads_AID='Stroud' WHERE Ads_ID='5'");Does any one know where I am going wrong? I had originally created a topic on my pagination not working, but I found out what the problem was. The topic I had created was irrelevant to what the problem was... but anyway, here's my situation: I've got a query that searches in a MySQL table for a certain value. Then it list's all the findings in a table (pretty simple). Anyway, I obviously want to have a pagination system to make it easier to manage the amount of data per page. The pagination works fine, it's used for another query that just pulls data (so NO WHERE clause is used!). That is what is causing the problem. I spent hours trying to figure out why this is happening, then I figured out that the only difference between the pagination that works and the one that doesn't is the query have the where clause. What happens when the where clause is used is that the pagination works fine on the first page, but if you click the link to go to a different page, the page is empty and turns up no results so the mysql data that is pulled is lost. So here is my code. I don't know exactly why the where clause causes the pagination to not work. Code: [Select] $conn = mysql_connect("$mysql_host","$mysql_user","$mysql_password") or trigger_error("SQL", E_USER_ERROR); $db = mysql_select_db("$mysql_database",$conn) or trigger_error("SQL", E_USER_ERROR); // find out how many rows are in the table $sql = "SELECT COUNT(*) FROM ACTIVE WHERE MODEL='$model'"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); $r = mysql_fetch_row($result); $numrows = $r[0]; // number of rows to show per page $rowsperpage = 5; // find out total pages $totalpages = ceil($numrows / $rowsperpage); // get the current page or set a default if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { // cast var as int $currentpage = (int) $_GET['currentpage']; } else { // default page num $currentpage = 1; } // end if // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; } // end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // end if // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; $sql = "SELECT * FROM ACTIVE WHERE MODEL='$model' ORDER BY INDEX_ID DESC LIMIT $offset, $rowsperpage"; $result = mysql_query($sql, $conn) or die('Error: ' . mysql_error()); echo " <table width=100% align=center border=1 class=\"mod\"><tr> <td align=center bgcolor=#00FFFF><b>Rating</b></td> <td align=center bgcolor=#00FFFF><b>Title</b></td> <td align=center bgcolor=#00FFFF><b>Make/Model</b></td> <td align=center bgcolor=#00FFFF><b>Type</b></td> <td align=center bgcolor=#00FFFF><b>Difficulty</b></td> <td align=center bgcolor=#00FFFF><b>Comments</b></td> <td align=center bgcolor=#00FFFF><b>Views</b></td> </tr>"; while ($row = mysql_fetch_assoc($result)) { { // Begin while $title = $row["TITLE"]; $type = $row["TYPE"]; $difficulty = $row["DIFFICULTY"]; $comments = $row["COMMENT_TOTAL"]; $id = $row['INDEX_ID']; $rating = $row["RATING_AVERAGE"]; $make = $row["MAKE"]; $model = $row["MODEL"]; $views = $row["HITS"]; echo " <tr> <td>$rating/10</td> <td><a href=\"mod.php?id=$id\">$title</a></td> <td>$make - $model</td> <td>$type</td> <td>$difficulty</td> <td>$comments</td> <td>$views</td> </tr>"; } } echo "</table><br />"; /****** build the pagination links ******/ echo "<center>"; // range of num links to show $range = 3; echo "<i>Page: </i>"; // if not on page 1, don't show back links if ($currentpage > 1) { // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a stylehref='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'>Previous</a> - "; } // end if // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " <b>$x</b> "; // if not current page... } else { // make it a link echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> "; } // end else } // end if } // end for // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " - <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>Next</a> "; } // end if /****** end build pagination links ******/ mysql_close($conn); } echo "$pagination</center>"; ?> I really appreciate the help! Thanks. |