I have this code:
public function updateOrder($num, $ufood, $uquan) {
$response = array();
mysql_query("SET NAMES 'utf8'");
foreach ($ufood as $index => $f) {
$result = mysql_query("SELECT food, quantity, uquantity FROM table1 WHERE food ='".$f."'") or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
$response['number rows'] = $no_of_rows;
if ($no_of_rows>0) {
while ($row = mysqli_fetch_array($result)); {
if (!$row['uquantity']) {
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
mysql_query($w);
$e = (int)$row['quantity'];
$q = (int)$uquan[$index];
$sum = $e+$q;
$s = (string)$sum;
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
mysql_query($d);
} else if($row['uquantity']) {
$c = (int)$row['uquantity'];
$q = (int)$uquan[$index];
$sumq = $c+$q;
$sq = (string)$sumq;
$d = "UPDATE table1 SET uquantity = '$sq' WHERE food = ".$row['$food']." ";
}
}
} else {
$string ="INSERT INTO table1(food,uquantity) VALUES ('".$f."','".$uquan[$index]."')";
$z = mysql_query($string);
}
}
}
Well i can not make this work, and i am trying all kinds of things put still it doesn't work.
So i have some questions:
Is this structure of foreach and while valid?
Though the $result query returns some rows from the database, when i try to use $row['quantity'], as a value, i get null.
In this code i receive some data from an android app, and i try to "see", if there are already entries for the type food of my db_table(table1). If there are entries i want the db to sum the quantity entry of the android sent, data with the one that are inside my db, and update the field. This is the basically it. But as i said when i try to use the data that comes from the database, i get null values.
Please if someone could give me some hint, cause I'm really stuck..
There are many problems with your code. I'm marking this answer as Community Wiki, and I invite others to edit and add things as they find them.
You may also consider posting to https://codereview.stackexchange.com/ instead, when you have so many mistakes, until you have a more specific question.
Bad variable interpolation
This line won't do what you want it to:
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
This is not quite valid PHP syntax. You can either concatenate expressions:
$w = "INSERT INTO table1(uquantity) VALUES ('".$uquan[$index]."')";
Or you can embed expressions in curly braces:
$w = "INSERT INTO table1(uquantity) VALUES ('{$uquan[$index]}')";
Or you can use a query parameter placeholder:
$w = "INSERT INTO table1(uquantity) VALUES (?)";
$stmt = mysqli_prepare($w) or die(mysqli_error());
$uqi = $uquan[$index];
mysqli_stmt_bind_param($stmt, "i", $uqi);
mysqli_stmt_execute($stmt);
Mixing MySQL APIs
You can't mix mysql_query() with mysqli_fetch_array(). PHP has more than one API for MySQL, and you can't mix them. You should standardize on using the mysqli API, because the older mysql API is now deprecated.
Semicolon defeats while loop
The semicolon after the while statement makes the loop a no-op, and when it terminates, the $row contains nothing.
while ($row = mysqli_fetch_array($result)); {
Should be:
while ($row = mysqli_fetch_array($result)) {
Using variables inappropriately
Referencing a $row key with a single-quoted variable is probably not what you mean, in multiple ways:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
The column name in the select-list of your earlier SELECT query is 'food', not '$food'.
Also, even if you meant to use a variable name $food as the key, putting it in single quotes would not use the value of the variable, it would be the literal string '$food'.
Failure to quote string literal?
Furthermore, you use a quoted literal for comparing to the food column in your SELECT query, which makes me think it might be a string.
So the UPDATE should be something like:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = '".$row['food']."' ";
Or:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = " . intval($row['food']);
Or preferably use parameters and a prepared query, then you don't need to worry about quotes or types:
$d = "UPDATE table1 SET quantity = ? WHERE food = ?";
. . .
Failure to check for errors
Every query might fail, either because you have a syntax error (e.g. a string without quoting), or because the table doesn't have a column by the name you reference, or privileges issues, etc.
Always check the return status of the query function when you run a SQL query. The function returns false if there's an error, and if that happens you must check the error message.
mysqli_query($mysqli, $d) or trigger_error(mysqli_error($mysqli), E_USER_ERROR);
Failure to execute the UPDATE
Your second update assigns a SQL query string to the variable $d, but then does not execute that update query at all!
Related
I am teaching myself php and MySQL, and right now I have a problem with MySQL.
I want to compare the phone number that the user put in with the phone number in MYSQL, and if it is in MYSQL to not register it again.
My code:
<?php
require_once 'connection/connection.php';
// Variables from HTML to php
$worker_Name = $_POST['workerNameFromHtml']; // worker Name
$worker_City = $_POST['workerCityFromHtml']; // workerCity
$worker_career = $_POST['workerCareerFromHtml']; // worker career
$worker_PhoneNumber = $_POST['workerPhonNumberFromHtml']; // worker Phone Number
$worker_SecondPhoneNumber = $_POST['workerSecondPhoneNumberFromHtml']; // worker Second Phone Number
$submt=$_POST['submitFromHtml'];
if($submt){
$qry = ( "SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'") or die(mysql_error());
$result = $connect->query($qry);
$num = $result->num_rows;
if ($num == 1) {
$here = "INSERT INTO workersTable VALUES('','$worker_Name','$worker_City','$worker_career','$worker_PhoneNumber','$worker_SecondPhoneNumber')";
$query = $connect->query($here);
print "Successfully added!";
}
else {print "This number has already been entered Thank you for your cooperation!";}}
$connect->close();
So far I have not found a solution to this problem.
your biggest problem here is that you are trying to include variables inside of a string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'"
If you want to do it this way, you need to concatenate your variables with your string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '".$worker_PhoneNumber."'"
Keep in mind if you do this you will want to sanitize your variables first to prevent SQL injections. Also, when you INSERT variables, you will actually want to use a prepared statement like this:
"INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
where the 1st set of values are the names of your columns in the database and the second set are your PHP variables you are putting into it.
Sorry, I'm new to php / mysql. I'm trying to change an existing script to take the results and then insert the value into the database.
This is what I've tried. I'm guessing I'm missing something or the syntax is wrong:
// unique reference number is generated.
// check if it exists or not
$query = "SELECT `ID_UNIQUE` FROM `tbl_referrals`
WHERE `ID_UNIQUE`='".$unique_ref."'";
$result = mysql_query($query) or die(mysql_error().' '.$query);
if (mysql_num_rows($result)==0) {
// We've found a unique number. Lets set the $unique_ref_found
// variable to true and exit the while loop
$unique_ref_found = true;
$sql = "INSERT INTO `tbl_referrals` (`ID_UNIQUE`)
VALUES
(`ID_UNIQUE`)";
}
}
echo 'Your reference number is: '.$unique_ref;
Ticks are for identifiers, single quotes are for string values:
$sql = "INSERT INTO `tbl_referrals` (`ID_UNIQUE`)
VALUES
('ID_UNIQUE')";
}
Hi all I have a form where I'm entering students marks for exams, what I am trying to do is enter multiple marks in at once...but it just is not working, could someone help please? It is adding only ONE result, doesn't enter all that I write in.
FORM Code:
The script does not know what is $i in this case.
Use for loop:
$mark=$_POST['mark'];
$time=$_POST['time'];
$meID=$_POST['meID'];
$sID=$_POST['sID'];
for($i = 0; $i < count($_POST['mark']); $i++) {
$_mark = mysql_escape_string($mark[$i]);
$_time = mysql_escape_string($time[$i]);
$_meID = mysql_escape_string($meID[$i]);
$_sID = mysql_escape_string($sID[$i]);
$sql = "INSERT INTO Marks (mark, time, meID, sID) VALUES ($_mark, $_time, $_meID, $_sID)";
$result = mysql_query($sql);
}
Additionally you will add each mark twice, because of two mysql_query() invocations. I've already deleted one from $sql variable in my answer. Also you have wrong variable names in the insert query.
I think the problem is with the variable names:
Following line:
$sql = "SELECT * FROM ModuleExamStudent WHERE mesID = '$mesID'";
But there is no $mesID. It should be $mes:
$sql = "SELECT * FROM ModuleExamStudent WHERE mesID = '$mes'";
Again:
$sql = mysql_query("INSERT INTO Marks (mark, time, meID, sID) VALUES ('$mark', '$time', '$meID', '$sID')");
Should be:
$sql = mysql_query("INSERT INTO Marks (mark, time, meID, sID) VALUES ('$_mark', '$_time', '$_meID', '$_sID')");
there is no mysql_escape_string . try replace this;
$_mark = mysql_escape_string($mark[$i]);
to
$_mark = mysql_real_escape_string($mark[$i]);
and put $_mark in the query instead of $mark
and replace all others also.
Yeah, a lot of mistakes in you're code.
Fuse michal.hubczyk and Ambrish answer to obtain wath you want.
If i can suggest another way to do it, i'll prefer to make only one query instead an elevated number of query succession inside a loop.
Try this method
Inserting multiple rows in a single SQL query?
and build your query in a way like this:
$sql = "INSERT INTO XX VALUES";
for($i=0;$i < count($_POST['mark']); $i++){
$_mark = mysql_escape_string($mark[$i]);
$_time = mysql_escape_string($time[$i]);
$_meID = mysql_escape_string($meID[$i]);
$_sID = mysql_escape_string($sID[$i]);
$sql .= "(".$_mark.",".$_time",".$_meID.",".$sID.")";
if($i<(count($_POST['mark']-1))){
$sql .= ",";
}
$result = mysql_query($sql);
Another suggestion is to use mysqli libray instead mysql ( http://php.net/mysqli)
OK So I'm trying to access a table called emg_quote I have the Quote ID so Im trying to get the Column Subject from the same row as this ID but for some reason All I'm getting is the first row in the entire table? Can any one figure out what I'm doing wrong? Here is my coding:
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE ".$quoteid."";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Are you using a custom object to wrap the native API's?
Either way it doesn't look right to me. You don't seem to be using the result of the query.
i.e.
$result = $mysqli->query($query);
$row = $result->fetch_row();
You have few bad practices in your code.
A. You lie on $quoteid to give you the correct where syntax. ie: ID=123
This is an highly unsafe method, because the user can change the it to Some-Important-Details='bla'
To extract more details from this table or others.
B. You should ALWAYS escape characters when receiving data from user, otherwise you easily subjected to SQL-Injections. And believe me you don't want it.
you have to use the checking after where.
use you column name before your $quoteid variable
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE quoteid=".$quoteid." LIMIT 1 ";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Remember : USE limit 1 when you search with primary key and you know that only 1 record will be searched. it reduce your processing time.
You might be missing the where column.
$sql = "SELECT subject FROM emg_quote WHERE quote_id=".$quoteid."";
^^^^^^^^
We also do not see weather something with your Db class is wrong.
You should in any case not directly put request variables into a database query.
$sql = "SELECT subject FROM emg_quote WHERE ID='".$quoteid."'";
You had not wrote your db fieldname in where condition
I've create database, which basically accept name and Id and answer string of
length 47,and my php code will grade the incoming results against the answer key I provided and number containing the count of correct answers will stored in database. this is information of my database.
database name is marking
and table called 'answer', which has 5 fields as follow
1) answer_id :int , not null, auto increament.
2) name: text
3)id : text
4)answers : text
5)correct : int
my question and problem is the function is working
// setup query
$q = mysql_query("INSERT INTO `answer` VALUES
(NULL,'$name', '$id','$answers','$correct')");
// run query
$result = mysql_query($q);
or in another way , nothing storing in my database ???
Thanks in advance.
this is the whole program.
<?php
error_reporting(E_ALL ^ E_STRICT);
// to turn error reporting off
error_reporting(0);
$name =$_POST['name'];
$id = $_POST['id'];
$answers = $_POST['answers'];
// check the length of string
if(strlen($answers) !=10)
{
print'your answer string must be 10';
return;
}
mysql_connect("localhost","root","");
mysql_select_db("marking");
$name = addslashes($name);
$id = addslashes($id);
$answers = addslashes($answers);
$answer_key = "abcfdbbjca";
$correct = 0;
for($i=0;$i<strlen($answer_key);$i++)
{
if($answer_key[$i] == $answers[$i])
$correct++;
}
// Setup query
$q = mysql_query("INSERT INTO `answer` VALUES ('$name', '$id','$answers','$correct')");
$result = mysql_query($q);
print 'Thnak you. You got' + $correct + 'of 10 answers correct';
?>
Try this:
// setup query
$q = "INSERT INTO `answer` (`name`, `id`, `answers`, `correct`) VALUES
('$name', '$id','$answers','$correct')";
//Run Query
$result = mysql_query($q) or die(mysql_error());
Also, you should avoid using mysql_ functions as they are in the process of being deprecated. Instead, I recommend you familiarize yourself with PDO.
Also, note, the or die(mysql_error()) portion should not be used in production code, only for debugging purposes.
Two things.
You are actually executing the query twice. mysql_query executes the query and returns the result resource. http://php.net/manual/en/function.mysql-query.php
And also, you are quoting the int column correct in your query, as far as I know, you can't do that (I could be wrong there).
$result = mysql_query("INSERT INTO `answer` VALUES (NULL,'$name', '$id','$answers',$correct)");
EDIT: Turns out I'm actually wrong, you may disregard my answer.