I am trying to update multiple rows in a single query. Data doesnt get updated in my code. I am trying to join the two tables. When user enters a no. The data from the 2 tables will be displayed which is connected through the foreign key.The data from the table1 gets updated. Where as the columns from the table 2 doesnt get updated. I need to update the second table based on unique id
if($_REQUEST["profile"] == "profile")
{
$Id = $_REQUEST["id"];
$firstname = mysql_real_escape_string($_REQUEST["firstname"]);
$serial = mysql_real_escape_string($_REQUEST["serial"]);
$dom = mysql_real_escape_string($_REQUEST["dom"]);
$idno = $_REQUEST["idno"];
$pow = mysql_real_escape_string(stripslashes($_REQUEST["pow"]));
$address = mysql_real_escape_string(stripslashes($_REQUEST["address"]));
$bookno = mysql_real_escape_string(stripslashes($_REQUEST["bookno"]));
$zone = mysql_real_escape_string(stripslashes($_REQUEST["zone"]));
$mobile = mysql_real_escape_string(stripslashes($_REQUEST["phone"]));
$phone = mysql_real_escape_string(stripslashes($_REQUEST["mobile"]));
$mothertongue=mysql_real_escape_string(stripslashes($_REQUEST["mothertongue"]));
$nof=mysql_real_escape_string(stripslashes($_REQUEST["nof"]));
$email=mysql_real_escape_string(stripslashes($_REQUEST["email"]));
$nom=$_REQUEST["nom"];
$nofemale=$_REQUEST["nofemale"];
mysql_query("UPDATE profile SET firstname='".$firstname."',serial='".$serial."',dom='".$dom."',idno='".$idno."',pow='".$pow."',address='".$address."',bookno='".$bookno."',
zone='".$zone."',phone='".$mobile."',mobile='".$phone."',mothertongue='".$mothertongue."',email='".$email."',nof='".$nof."',nom='".$nom."',nofemale='".$nofemale."' WHERE id = '".$_POST['id']."' " ) or die(mysql_error());
for($i=0;$i<count($_REQUEST['slno1']);$i++)
{
$mid=$_REQUEST['mid'][$i];
$slno1 = mysql_real_escape_string(stripslashes($_REQUEST["slno1"][$i]));
$name1 = mysql_real_escape_string(stripslashes($_REQUEST["name1"][$i]));
$rhof1 = mysql_real_escape_string(stripslashes($_REQUEST["rhof1"][$i]));
$dob1 = mysql_real_escape_string(stripslashes($_REQUEST["dob1"][$i]));
$dobapt1 = mysql_real_escape_string(stripslashes($_REQUEST["dobapt1"][$i]));
$doc1 = mysql_real_escape_string(stripslashes($_REQUEST["doc1"][$i]));
$doconf1 = mysql_real_escape_string(stripslashes($_REQUEST["doconf1"][$i]));
$qualification1 = mysql_real_escape_string(stripslashes($_REQUEST["qualification1"][$i]));
$school1 = mysql_real_escape_string(stripslashes($_REQUEST["school1"][$i]));
$occupation1 = mysql_real_escape_string(stripslashes($_REQUEST["occupation1"][$i]));
$run=mysql_query("UPDATE member SET
slno1='".$slno1."',name1='".$name1."',rhof1='".$rhof1."',dob1='".$dob1."',dobapt1='".$dobapt1."',doc1='".$doc1."',doconf1='".$doconf1."',qualification1='".$qualification1."' WHERE mid = '".$mid."' " ) or die(mysql_error());
}
}
Please use PDO so you won't have to escape strings and so your code gets simpler to read. Your query has too many quotes used and this alone can make it easy to fail. Please use following examples and this should help you succeed.
Basic PDO update:
https://www.w3schools.com/php/php_mysql_update.asp
Bind Params:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
In your query you are using $_POST['mid'] instead of that you should use $mid which you are already reading as
$mid=$_REQUEST['mid'][$i];
As per my understanding UPDATE query is used to update a limited number of records if using the where condition. So the only way that I can think of is using an INSERT query with ON DUPLICATE KEY UPDATE clause. Try the below code:
for($i=0;$i<count($_REQUEST['mid']);$i++) {
$mid[] = $_REQUEST['mid'][$i];
$slno1[] = mysql_real_escape_string(stripslashes($_REQUEST["slno1"][$i]));
$name1[] = mysql_real_escape_string(stripslashes($_REQUEST["name1"][$i]));
$rhof1[] = mysql_real_escape_string(stripslashes($_REQUEST["rhof1"][$i]));
$dob1[] = mysql_real_escape_string(stripslashes($_REQUEST["dob1"][$i]));
$dobapt1[] = mysql_real_escape_string(stripslashes($_REQUEST["dobapt1"][$i]));
$doc1[] = mysql_real_escape_string(stripslashes($_REQUEST["doc1"][$i]));
$doconf1[] = mysql_real_escape_string(stripslashes($_REQUEST["doconf1"][$i]));
$qualification1[] = mysql_real_escape_string(stripslashes($_REQUEST["qualification1"][$i]));
$school1[] = mysql_real_escape_string(stripslashes($_REQUEST["school1"][$i]));
$occupation1[] = mysql_real_escape_string(stripslashes($_REQUEST["occupation1"][$i]));
}
$query = "INSERT INTO `member` (`mid`,`slno1`,`name1`,`rhof1`,`dob1`,`dobapt1`,`doc1`,`doconf1`,`qualification1`) VALUES ";
for ($i = 0; $i < count($mid); $i++) {
$query .= "('".$mid[$i]."','".$slno1[$i]."','".$name1[$i]."','".$rhof1[$i]."','".$dob1[$i]."','".$dobapt1[$i]."','".$doc1[$i]."','".$doconf1[$i]."','".$qualification1[$i]."')";
if ($i != (count($mid) - 1)) {
$query .= ',';
}
}
$query .= ' ON DUPLICATE KEY UPDATE `slno1` = VALUES(`slno1`), `name1` = VALUES(`name1`), `rhof1` = VALUES(`rhof1`), `dob1` = VALUES(`dob1`), `dobapt1` = VALUES(`dobapt1`), `doc1` = VALUES(`doc1`), `doconf1` = VALUES(`doconf1`), `qualification1` = VALUES(`qualification1`);';
$run=mysql_query($query) or die(mysql_error());
Hope This Helps.
Related
Using PHP + Oracle 12c
I'm trying to insert many rows but i got an error "oci_execute(): ORA-00001: unique constraint (S95417.FIRMA__IDX)" This is strange for me because in loop i'm getting last id and incrementing it.
I used debbuger and (On INSERT) i'm getting last id but incrementing is not working.
Could you tell me why?
Data which i added
INSERT INTO FIRMA VALUES(18,MICROSOFT,2432213715,2020-03-26,23)
INSERT INTO FIRMA VALUES(19,APPLE,7512202082,2020-03-26,42)
SELECT NVL(MAX(firmaid),0)+1
I made code very similar using that for other tables and it's working fine.
My code:
$ile_razy = $_POST['liczba_powtorzen'];
$firma = "SELECT * FROM FIRMA";
$c = oci_connect($username, $password, $database);
if (!$c) {
$m = oci_error();
trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}
$file = 'firma.txt';
$current = file_get_contents($file);
for ($i = 1; $i <= $ile_razy; $i++) {
$nazwa = randCompanyName();
$nip = randNIP();
$dataWspolpracy = date("Y-m-d");
$ids_array = array();
$adresid = "SELECT adresid FROM ADRES";
$stmtt = oci_parse($c, $adresid);
$result = oci_execute($stmtt);
while($row = oci_fetch_array($stmtt))
{
$ids_array[] = $row['ADRESID'];
}
$randIndex = array_rand($ids_array);
$adresId = $ids_array[$randIndex];
// HERE IS PROBLEM
$firmaQuery = "INSERT INTO FIRMA SELECT NVL(MAX(firmaid),0) + 1,'$nazwa', '$nip', '$dataWspolpracy', '$adresId' from FIRMA";
$ex = oci_parse($c,$firmaQuery);
// "zapytanie" is working fine
$zapytanie = "SELECT NVL(MAX(firmaid),0)+1 from FIRMA";
$stmt = oci_parse($c, $zapytanie);
$results = oci_execute($stmt);
while($row = oci_fetch_assoc($stmt)){
$rowid = $row["NVL(MAX(FIRMAID),0)+1"];
}
$firmaIdForTxt = "INSERT INTO FIRMA VALUES(".$rowid.",".$nazwa.",".$nip.",".$dataWspolpracy.",".$adresId.")";
echo $rowid. ", ";
oci_execute($ex);
$current .= $i. ".".$firmaIdForTxt."\n";
file_put_contents($file, $current);
}
In my db
I have changed that but error still appears
You can make your FIRMAID an identity column : Oracle will handle the increment internally, and it is much more safer for your data.
Then you can insert your data with this query :
INSERT INTO FIRMA(nazwa, nip, datawspolpracy, adresid) VALUES('$nazwa', '$nip', '$dataWspolpracy', '$adresId')
NOTE : this is for a quick answer, for a safer solution and avoid SQL injections, use prepared statements : PHP oci examples (See example #2)
$upload_files=implode(' ',$_GET['upload_files']);
$upload_user=",".$_GET['upload_user'];
echo $upload_files;
$sql = "UPDATE {$db_pr}files SET userID = CONCAT(userID,'".$upload_user."') WHERE id IN ('".$upload_files."')";
IN takes a comma-delimited string I believe.
try:
$upload_files=implode("','",$_GET['upload_files']);
Well, I got the solution. I used for loop to achieve the result.
$upload_files=$_GET['upload_files'];
$upload_user=",".$_GET['upload_user'];
for ($i = 0, $count = count($upload_files); $i <= $count; $i++) {
$sql = "UPDATE {$db_pr}files SET userID = CONCAT(userID,'".$upload_user."') WHERE id = '".$upload_files[$i]."'";
$result = mysqli_query($mysqli,$sql) or die("Error occurred - tried to update file.");
}
echo "<div class='loginMessage loginSuccess'>Assigned Successfully!!!</div>";
I am trying to return a list of users' first and last names in JSON format in PHP.
My PHP looks something like:
$_Query = '
SELECT
Fname,Lname
FROM
users
WHERE
number = "'.$_REQUEST['number'].'"
;';
$SQLResult = mysql_query($_Query) or die(mysql_error());
$_UserData = array();
if(mysql_num_rows($SQLResult) <> 0){
while($SQLRow = mysql_fetch_array($SQLResult)){
$_UserData['Fname'] = $SQLRow['Fname'];
$_UserData['Lname'] = $SQLRow['Lname'];
}
}
echo json_encode($_UserData);
I expect more than one row in the format
{"Fname":["First_name1","First_name2"],"Lname":["Last_name1","Last_name2"]}
of course. However the script returns the last row with the correct conditions
{"Fname":"Steve","Lname":"LastName"}
The MySQl server returns what it should with the same query.
+--------------+-------------+
| Fname | Lname |
+--------------+-------------+
| First_name1 | Last_name1 |
| First_name2 | Last_name2 |
+--------------+-------------+
Why is this happening and how should I go about fixing it? Thanks!
Try this:
while($SQLRow = mysql_fetch_array($SQLResult)){
$_UserData[] = $SQLRow;
}
In your example you are essentially overwriting the $_UserData array for every new row, hence the missing rows.
UPDATE:
This will make the JSON string look more the way you want it.
while($SQLRow = mysql_fetch_assoc($SQLResult)){
$_UserData['Fname'][] = $SQLRow['Fname'];
$_UserData['Lname'][] = $SQLRow['Lname'];
}
$_UserData['Fname'] = $SQLRow['Fname'];
$_UserData['Lname'] = $SQLRow['Lname'];
You're repeatedly setting the same two elements of _UserData, rather than appending new values to the array.
Your loop overrides the values in $_UserData array.
You should append each row to the array.
In addition, please note that you should escape your input.
Your code should look like this:
$_Query = '
SELECT
Fname,Lname
FROM
users
WHERE
number = "'.(int)$_REQUEST['number'].'"
;';
$SQLResult = mysql_query($_Query) or die(mysql_error());
$_UserData = array();
if(mysql_num_rows($SQLResult) <> 0){
while($SQLRow = mysql_fetch_array($SQLResult)){
$_UserData[] = $SQLRow;
}
}
echo json_encode($_UserData);
Try with this:
$_UserData = array();
if(mysql_num_rows($SQLResult) <> 0){
$i = 0;
while($SQLRow = mysql_fetch_array($SQLResult)){
$_UserData[$i]['Fname'] = $SQLRow['Fname'];
$_UserData[$i]['Lname'] = $SQLRow['Lname'];
$i++;
}
I'm sure you'll kick yourself when you realise that you've only assigned to 1 element of your $_UserData array.
Should be something like:
$_UserData = array();
if(mysql_num_rows($SQLResult) <> 0){
while($SQLRow = mysql_fetch_array($SQLResult)){
// Either...
// Create a new entry in $_UserData with same structure and contents as $SQLRow
$_UserData[] = $SQLRow;
// OR more specific - say if the structures aren't identical
// $DataRow=array();
// $DataRow['Fname'] = $SQLRow['Fname'];
// $DataRow['Lname'] = $SQLRow['Lname'];
// $_UserData[] = $DataRow;
}
}
Cheers
I have a meal/recipe database, used for creating daily meal plans. I need to create 3 different select lists (breakfast, lunch, dinner) to display the available recipe options, for each meal_name.
As of now I'm using separate queries for each of the above, and separate builds to display the results for each list.
The query for Lunch:
// Lunch options
$sql = "SELECT plan_date,
plan_meal,
plan_recipe,
recipe_name,
recipe_serving_size
FROM recipe_plans
LEFT JOIN $table_meals ON meal_id = plan_meal
LEFT JOIN $table_recipes ON recipe_id = plan_recipe
WHERE plan_date = '".$date."'
AND meal_name = 'Lunch'
AND plan_owner = '".$user_name."'
ORDER BY recipe_name";
$rc = $DB_LINK->Execute($sql);
DBUtils::checkResult($rc, NULL, NULL, $sql);
// Scan the rows of the SQL result
while (!$rc->EOF) {
$recipeList[($rc->fields['plan_recipe'])] = $rc->fields['recipe_name'] . " (" . $rc->fields['recipe_serving_size'] . ")";
$rc->MoveNext();
}
and the build:
// Scan the fields in the SQL result row
// Print all existing Meals, and some new ones
$minShow = 1;
$maxShow = 1; // only build 1 while testing
for ($i = 0; $i < (isset($MealPlanObj->mealplanItems[$date]) && ($i < $maxShow) ? count($MealPlanObj->mealplanItems[$date]) : 0) + $minShow; $i++) {
if ($i < (isset($MealPlanObj->mealplanItems[$date]) ? count($MealPlanObj->mealplanItems[$date]) : 0)) {
// If it is an existing meal item, then set it
$meal = $MealPlanObj->mealplanItems[$date][$i]['meal']; // meal_id
$servings = $MealPlanObj->mealplanItems[$date][$i]['servings'];
$recipe = $MealPlanObj->mealplanItems[$date][$i]['id']; // recipe_id
} else {
// It is a new one, give it blank values
$meal = NULL;
$servings = $defaultServings;
$recipe = NULL;
}
// The HTML Code to build the select list for 'Lunch'
}
The above code has been duplicated for each meal_name, because that's where my limited skills have left me, lol.
The question is: rather than writing a separate select and build statement for each of the 3 conditions (breakfast, lunch, dinner), how can I write just 1, to output them all?
You already used variables to build the SQL query, so you can introduce just another variable like $meal_name. This variable you can apply to your SQL statement. Instead of:
$sql = "SELECT mplan_date,
...
AND meal_name = 'Lunch'
...
you will write then:
$meal_name = 'Lunch';
...
$sql = "SELECT mplan_date,
...
AND meal_name = '" . mysqli_real_escape_string($meal_name) . "'
...
Note the use of the function mysqli_real_escape_string(), although not absolutely necessary in this example, it's very important to escape all variables you add to an SQL statement, if you are not absolutely sure what's inside the variable. Your example code is vulnerable to SQL-injection.
After that you can go a step further and pack the code into a function:
function buildSqlQuery($meal_name, $date, $user_name)
{
$sql = "SELECT mplan_date,
...
ORDER BY recipe_name";
return $sql;
}
$sqlForBreakfast = buildSqlQuery('Breakfast', '2000-01-01', 'teddy');
$sqlForLunch = buildSqlQuery('Lunch', '2000-01-01', 'teddy');
$sqlForDinner = buildSqlQuery('Dinner', '2000-01-01', 'teddy');
all im try do do is add variables that are within mysql.
I thought this would be simple but not proving to be and im not really getting anywhere.
Is it even possible to add values from mysql?
I'm sure it probably something simple, as always, any guidance is appreciated.
Thanks
$query = mysql_query("SELECT * FROM users WHERE ID ='$userid'");
$numrows = mysql_num_rows($query);
if($numrows ==1){
$row = mysql_fetch_assoc($query);
$id = $row['uid'];
$name = $row['name'];
$angles = $row['angles'];
$decimals = $row['decimals'];
$multiplication = $row['multiplication'];
$probability = $row['probability'];
$sequences = $row['sequences'];
$symmetry = $row['symmetry'];
}
$sum = $sequences + $symmetry;
print ("$sum");
Solved the issue. the query should read ....WHERE uid ='$userid'");!
You could also do the calculation by the database by a query like this:
SELECT uid, name, angles, (sequences + symmetry) AS mysum FROM users WHERE ID ='$userid'