I have this php script.
$cwZ = count($wiegen_zutat);
$cwM = count($wiegen_menge);
$cwS = count($wiegen_schritt);
if($cwM == $cwS and $cwM == $cwZ and $cwZ == $cwS){
for($x = 0; $x < $cwZ; $x++){
$aktZuat = $wiegenZutat[$x];
$qr = "SELECT ID_Zutat FROM Zutaten WHERE Name='$aktZutat' LIMIT 1";
$id_get = mysqli_query($verbindung,$qr );
$id = mysqli_fetch_array($id_get);
$zuatenID = $id['ID_Zutat'];
echo $id['ID_Zutat'];
echo $zutatenID;
$sql3 = "INSERT INTO Wiegen (ID_Zutat, Menge) VALUES ('$zutatenID', '$wiegenMenge[$x]')";
$wiegenEintragen = mysqli_query($verbindung, $sql3);
}
}
$wiegen_zutat, _menge, _schritt are all three arrays which contain the information from my form.
I go through the first array, and check the variable against a table which contains the ingredients for my website. I want to get the id of a ingredient which was added some steps before and add it into another table.
The problem is that neither the echos or the query are working.
What am I missing?
Please don't get confused by the name of the variables, I'm german :)
Best regards
Related
I have to create a PHP web page with two text fields in which the user can enter minimum and maximum item prices from a SQL database. So I have items with prices. For example, if a user wants to see items between the prices 4 and 15, he can submit it and then it will show only the items in that price range. How can I do this? How to echo this?
Thank you!
I have this so far:
$min=$_POST["minimum"];
$max=&$_POST["maximum"];
$result = mysqli_query($con,"SELECT * FROM items WHERE selling price BETWEEN {$min}+1 AND {$max}");
Apart from a major SQL Injection issue, your script is looking fine. Just some small typs and syntax errors. Compare this one to yours:
$min=(int)$_POST["minimum"];
$max=(int)$_POST["maximum"];
$result = mysqli_query($con,"SELECT * FROM items WHERE selling_price BETWEEN {$min}+1 AND {$max}");
So, what did I change?
At least cast posted values to int to remove the chance of anyone injecting malicious SQL code into your query. You should use proper escaping in the future
You dont need to add the & character before in line two. You dont need to assign the value by reference. just assign the plain old way
column and table names can not conain spaces in MySQL. Are you sure that is the correct name of the column? Maybe there was an underscore?
One of the many safer and simpler ways of doing that would be
$dsn = "mysql:dbname=test;host=127.0.0.1";
$dbh = new PDO($dsn, 'username', 'password');
if(isset($_POST["minimum"]) && isset($_POST["maximum"]))
{
$min=floatval($_POST["minimum"]); //+1 is not needed
$max=floatval($_POST["maximum"]);
$sth = $dbh->prepare("SELECT * FROM items WHERE selling_price BETWEEN ? AND ?");
$sth->execute(array($min,$max));
while($row = $sth->fetch(PDO::FETCH_OBJ))
{
print_r($row);
}
}
That should do the trick for you:
if(isset($_POST['minimum'])){
$min = $_POST['minimum'];
}else{
$min = '';
}
if(isset($_POST['maximum'])){
$max = $_POST['maximum'];
}else{
$max = '';
}
$sql = "SELECT * FROM item WHERE selling_brice > '$min' AND selling_price < '$max'";
$query = mysqli_query($con, $sql);
$count = mysqli_num_rows($query);
if($query == true && $count > 0 ){
while ($row = mysqli_fetch_assoc($query)){
$price .= $row['selling_price'];
$price .= '<br />'
}
echo $price;
}else{
echo "NO results to Display";
}
Ofcourse this is not the best programing mysql injections, your query uses * etc....but this should work.
Here I'm trying to insert the datas again into database new table (with quantity & customer details). $grocery_id and $grocery_item values are fetch from database. $customername, $customermobile, $groqty values are user will enter the details in that appropriate textfield.
When I execute this code ($groceryid, $groceryitem) -> These two column always stored the last row values. Because I've put the query outside of foreach loop. Here is my problem. If I put the query inside the foreach it works fine. But, quantity values doesn't work properly. So, How can I execute the query properly (outside of foreach loop)?
<?php
if(isset($_POST['submit']))
{
$grocery_id = $rowid;
$grocery_item = $rowsitem;
$customername = $_POST['customername'];
$customermobile = $_POST['customermobile'];
$groqty = $_POST['groceryquantity'];
for($i = 0; $i < sizeof($groqty); $i++)
{
$groqtys = $groqty[$i];
foreach($grocery_id as $key => $index_id )
{
}
$sql = "INSERT INTO ".customer_order." SET grocery_id = '$index_id' , grocery_item = '$grocery_item[$key]', customername = '$customername', customermobile = '$customermobile', quantity = '$groqtys' ";
mysql_query($sql,$CN);
$response = asort_form_ok("Your order successfully submitted. We will deliver you soon.");
}
}
?>
You could simply use one foreach loop considering the index values of $grocery_id and $groqty are the same.
Try:
<?php
if (isset($_POST['submit']))
{
$grocery_id = $rowid;
$grocery_item = $rowsitem;
// sanitizing your values
$customername = mysql_real_escape_string($_POST['customername']);
$customermobile = mysql_real_escape_string($_POST['customermobile']);
$groqty = array_map('mysql_real_escape_string', $_POST['groceryquantity']);
foreach($grocery_id as $key => $index_id)
{
$sql = "INSERT INTO " . customer_order . " SET grocery_id = '$index_id' , grocery_item = '$grocery_item[$key]', customername = '$customername', customermobile = '$customermobile', quantity = '$groqty[$key]' ";
mysql_query($sql, $CN);
$response = asort_form_ok("Your order successfully submitted. We will deliver you soon.");
}
}
?>
Also note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
So I currently have a random number being generated in PHP and I want to know how I go about updating the row number in my selected table. Code below:
$sxiq = mysql_query("SELECT * FROM `starting_eleven` WHERE `team_id`=$uid");
$sxir = mysql_fetch_row($sxiq);
$first = rand(1,11);
$stat_changed = rand(11,31);
$up_or_down = rand(1,2);
if ($up_or_down == 1) {
$player_name = explode(" ", $sxir[$first]);
$fn = $player_name[0];
$ln = $player_name[1];
$statq = mysql_query("SELECT * FROM `players` WHERE `first_name`=$fn AND `last_name`=$ln AND `user_id`=".$_SESSION['user_id']);
$statr = mysql_fetch_row($statq);
$stat = $statr[0];
}
I would like to update the row $stat_changed from the database, but I'm not sure if this is possible without doing a long if statement, telling the code if $stat_changed = 13 $stat = pace or something along those lines, but if this is the way it must be done then I'll have to. Just thought I'd see if there was any other simpler ways of doing this.
Thanks in advance
if ($stat_changed == 13) {
//insert UPDATE statement here
}
I've tried searching for answers to my problem but no one else seems to have had this problem! I'm basically trying to select in php using the WHERE statement, I want to compare my $ID to variables stores in an array called $resultAddID2. This array has values [1,2,1]; if I try accessing $resultAddID2[0] it works fine, but if I try to do it with $resultAddID2[1] or $resultAddID2[2] it doesn't work at all! I'm sure this is something silly but for the life of me I just can NOT figure it out! Any help would be much appreciated, thank you.
Here's the part where I try to do this:
$resultAddID = mysql_query("SELECT ADDRESS_ID FROM hospital");
while($resultAddID1=mysql_fetch_array($resultAddID)){
$resultAddID2[]=$resultAddID1['ADDRESS_ID'];
for ($i = 0; $i <= 2; $i++) {
$resultAddT = mysql_query("SELECT * FROM address WHERE ID = $resultAddID2[]");
$resultAddTm= mysql_fetch_array($resultAddT);
$resultAddT2[]=$resultAddTm['GOVER_ID'];
}
}
$response["hospADD"]= $resultAddT2;
You should add {}'s like
$resultAddT = mysql_query("SELECT * FROM address WHERE ID = {$resultAddID2[$i]}");
It would be better if you did something like this because you are querying the second item too many times
$resultAddID = mysql_query("SELECT ADDRESS_ID FROM hospital");
while($resultAddID1=mysql_fetch_array($resultAddID)){
$resultAddID2[]=$resultAddID1['ADDRESS_ID'];
}
for ($i = 0; $i <= 2; $i++) {
$resultAddT = mysql_query("SELECT * FROM address WHERE ID = {$resultAddID2[$i]}");
$resultAddTm= mysql_fetch_array($resultAddT);
$resultAddT2[] = $resultAddTm['GOVER_ID'];
}
$response["hospADD"]= $resultAddT2;
OR simpler yet:
$resultAddID = mysql_query("SELECT ADDRESS_ID FROM hospital");
while($resultAddID1=mysql_fetch_array($resultAddID)){
$resultAddT = mysql_query("SELECT * FROM address WHERE ID = {$resultAddID1['ADDRESS_ID']}");
$resultAddTm= mysql_fetch_array($resultAddT);
$resultAddT2[] = $resultAddTm['GOVER_ID'];
}
$response["hospADD"]= $resultAddT;
i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.