I've a html form where 3 field exist which process by PHP.
1) Password 2) Upload Logo and 3) Tag Line field.
So user can upload either password or logo or tag line or all field or 2 field. So that I run following query. But it's not Edit the DB. Is that ok or any suggestions of your ?
$update = mysql_query("UPDATE e_users SET email = '$email'");
if(!empty($pass_post))
{
$update .= "pass = '$pass', salt = '$random_salt'";
}
if(!empty($logo_text))
{
$update .= "logo_text = '$logo_text'";
}
if(!empty($file))
{
$update .= "logo = '$student_pic'";
}
$update .= "WHERE uname = '$ses_user'";
Thank You.
You left out the commas when you appended additional fields to the query, and you should have a space before WHERE (not strictly necessary in this case, since all your assignments end with a quote, but it's a good idea). And you were trying to concatenate to a mysql result resource, not the SQL string.
$update = "UPDATE e_users SET email = '$email'";
if(!empty($pass_post))
{
$update .= ", pass = '$pass', salt = '$random_salt'";
}
if(!empty($logo_text))
{
$update .= ", logo_text = '$logo_text'";
}
if(!empty($file))
{
$update .= ", logo = '$student_pic'";
}
$update .= " WHERE uname = '$ses_user'";
$result = mysql_query($update);
Related
I want to retrieve data from three tables using some condition and then insert/update in another three tables. This is a very simple process, the script of which is developed in php. But the catch is that the records retrieved from each table is 100k+. PHP script runs only with small number of records and gives time out error for large data. Can anyone please suggest how to solve this issue. All the three tables data needs to be fetched at runtime. Below is my php script which gives timeout error
switch($action){
case 'tequipebudget':
$oldPresta = budPrestaDataTransfer::getOldPresta('tequipebudget');
$budProviderBudget = budPrestaDataTransfer::updatebudProviderBudget($oldPresta, 'budproviderbudget', 3);
break;
case 'tequipebudgetjum':
$oldPrestaJum = budPrestaDataTransfer::getOldPresta('tequipebudgetjum');
$budProviderBudgetJum = budPrestaDataTransfer::updatebudProviderBudget($oldPrestaJum, 'budproviderbudgetjum', 3);
break;
case 'tequipebudgetavhisto':
$oldPrestaAvHisto = budPrestaDataTransfer::getOldPresta('tequipebudgetavhisto');
$budProviderBudgetAvHisto = budPrestaDataTransfer::updatebudProviderBudget($oldPrestaAvHisto, 'budproviderbudgetavhisto', 3);
break;
}
static public function getOldPresta($table) {
$sql = "SELECT Annee, CodeEntite, CodeProjet, MtBudgetAEquipeKE, projet_id";
if($table == 'tequipebudgetavhisto') {
$sql .= " ,avenant_id ";
}
$sql .= " FROM ".$table." WHERE Annee < 2020 ";
$dbObj = budPDO::getInstance();
$prestaList = $dbObj->getAllResults($sql);
return $prestaList;
}
static public function updatebudProviderBudget($prestaList, $table, $autreId) {
foreach($oldPresta as $key=>$val) {
$sql = "SELECT count(*) as cnt FROM ".$table." WHERE Annee = '".$val['Annee']."' AND CodeEntite = '".$val['CodeEntite']."' AND
CodeProjet = '".$val['CodeProjet']."' AND projet_id = '".$val['projet_id']."' AND provider_id = '".$oldPresta['AuterId']."' ";
$dbObj = budPDO::getInstance();
$res = $dbObj->getOneRow($sql);
if($res['cnt'] == 0){ // record does not exists in table
$update = "INSERT INTO ".$table." SET Annee = '".$val['Annee']."', CodeEntite = '".$val['CodeEntite']."',
CodeProjet = '".$val['CodeProjet']."', cost = '".$val['MtBudgetAEquipeKE']."' ,
projet_id = '".$val['projet_id']."', provider_id = '".$autreId."',
addedon_date = '".NOW_CONST."' ";
if($table == 'budproviderbudgetavhisto') {
$update .= " ,avenant_id= '".$val['avenant_id']."' ";
}
}else {
$update = "UPDATE ".$table." SET Annee = '".$val['Annee']."', CodeEntite = '".$val['CodeEntite']."',
CodeProjet = '".$val['CodeProjet']."', cost = '".$val['MtBudgetAEquipeKE']."' ,
projet_id = '".$val['projet_id']."', provider_id = '".$autreId."',
modifiedon_date = '".NOW_CONST."' ";
if($table == 'budproviderbudgetavhisto') {
$update .= " ,avenant_id= '".$val['avenant_id']."' ";
}
$update .= " WHERE Annee = '".$val['Annee']."' AND CodeEntite = '".$val['CodeEntite']."' AND
CodeProjet = '".$val['CodeProjet']."' AND projet_id = '".$val['projet_id']."' AND provider_id = '".$autreId."' ";
if($table == 'budproviderbudgetavhisto') {
$update .= " AND avenant_id= '".$val['avenant_id']."' ";
}
}
//echo "update -- " . $update. "<br><br>";
$sth = $dbObj->pdo->prepare($update);
$exec = $sth->execute();
}
}
You could increase the timeout in your PHP settings.
ini_set('max_execution_time','{number of seconds}');
Then you will probably also have to increase the memory limit.
ini_set('memory_limit', '2GB');
But it would be better to leave large data logic to the database. So if I were you, I would write a stored procedure / function and execute it with PHP only exec
i am trying to add an if condition to mysql query to only update a certain field if condition is met, here is my code below, but i keep getting this error
ERROR
{ "error": { "message":SQLSTATE[HY093]: Invalid parameter number:
parameter was not defined } }
CODE
$ok = 1;
$sql = "UPDATE users SET
fn = :first,
ln = :last
";
if($ok == 1){
$sql .= ",phone = :phone";
}
$sql .= "WHERE users.id = :id";
Keep space between your concatenation,
$ok = 1;
$sql = "UPDATE users SET
fn = :first,
ln = :last";
if($ok == 1){
$sql .= ", phone = :phone ";
}
$sql .= " WHERE users.id = :id";
I think you are missing a space
$sql =
"UPDATE users SET
fn = :first,
ln = :last
,phone = :phoneWHERE users.id = :id"
code:
if(isset($_POST["add"]))
{
extract($_POST);
$facilities = $_POST['facilities'];
$chk="";
foreach($facilities as $chk1)
{
$chk .= $chk1.",";
}
$exam = $_POST['exam'];
$chks="";
foreach($exam as $chked)
{
$chks .= $chked.",";
}
$filename = $_FILES['college_image']['name'];
$path = "college_banner/";
$move=move_uploaded_file($_FILES['college_image']['tmp_name'],$path.$_FILES['college_image']['name']);
$filename2 = $_FILES['logo']['name'];
$path2 = "college_logo/";
$move=move_uploaded_file($_FILES['logo']['tmp_name'],$path2.$_FILES['logo']['name']);
echo "insert into all_colleges(college_name,establish,approve,affiliated,address,website,about_us,city,courses,logo,college_image,phone,field,tag,video1,video2,facilities,courses_fee,short_name,state,exams,form_fee,college_commission,client_commission,form_type)values('$name','$establish','$approve','$affiliated','$address','$website','$about_us','$city','$course','$filename2','$filename','$phone2','$field','$tag','$video1','$video2','$chk','$fee','$short','$state','$chks','$form_fee','$college_commission','$client_commission','$form_type')";
$result = mysqli_query($link,$sql2);
if($result == true)
{
$msg .= "<h5 style='color:green;'>Successfull</h5>";
}
else
{
$msg .= "<h5 style='color:red;'>Error</h5>";
}
}
In database I have an auto_increment id i.e. college_id but when I remove auto_increment over college_id then it show successfull message when click on add button instead of error. So, how can I fix this problem ?
Thank You
It doesn't matter with you college_id just make sure if it is AUTO_INCREMENT then it must be PRIMARY KEY.
And in SQL query you are not assigning query to your $sql2 variable so use
echo $sql2 = "insert into all_colleges ...";
//---^ assign query in $sql2
$result = mysqli_query($link,$sql2); // <-- you are passing $sql2
1 more thing you can use implode() without using loops for checked values in a single statement like,
$chk= = implode(',',$_POST['facilities']);
I have a problem with a "unknown" column.
This is the error I get back in firebug.
ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'admin' in 'where clause'UPDATE users SET session_key = 1234567890 WHERE username = 'admin'
this is the parameters and call statement
$table = 'users';
$fields_vals = array( 'session_key' => $session_key );
$where = array('username' => $username);
$dbResult = $this->DB->sql_update($fields_vals, $table, $where);
/*
* UPDATE
* $data -> assoc array containing (field => value) to be UPDATED.
* $where -> Where clause (only a single argument)
* $table -> to be updated
*/
public function sql_update($fieldsVals, $table, $where)
{
try {
//Values to be updated in in a assoc array
//Extract values and fields and concatenate with '=' ( field = value )
$upd_string = '';
foreach($fieldsVals as $name => $value){
$upd_string .= $name .' = :'. $name .' ,';
}
//Trim last comma that was appended
$upd_string = rtrim($upd_string, ',');
// Formulate the where clause
$where_str = '';
foreach($where as $wName => $wValue){
$where_str .= "$wName = $wValue";
}
//Set Query
//$query = "UPDATE {$table} SET {$upd_string} WHERE $where_str";
// THIS IS WHERE I EXPLICITLY RAN THE QUERY, BUT GOT EXACTLY THE SAME ERROR.
$query = "UPDATE users SET session_key = 1234567890 WHERE username = 'admin'";
$stmt = $this->conn->prepare($query);
//Exec
foreach($fieldsVals as $k => &$v){
$stmt->bindParam(":{$k}", $v);
}
$stmt->execute();
return true;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
return false;
}
}
Here is proof that the column does exist.
PLEASE NOTE -> where username = 'admin'
Try passing your WHERE attribute in as a prepared variable:
$query = "UPDATE users SET session_key = 1234567890 WHERE username = :username";
$fieldsVals[":username"] = "admin";
$where_str .= "$wName = '$wValue'";
Otherwise your query comes as "WHERE username = admin"
What you should do to use prepared statements for the whole query, so you should change your function from the current one into:
function sql_update($fieldsVals, $table, $where)
{
//Values to be updated in in a assoc array
//Extract values and fields and concatenate with '=' ( field = value )
$upd_string = '';
foreach ($fieldsVals as $name => $value) {
$upd_string .= $name . ' = :set_' . $name . ' ,';
}
//Trim last comma that was appended
$upd_string = rtrim($upd_string, ',');
// Formulate the where clause
$where_str = '';
foreach ($where as $wName => $wValue) {
$where_str .= $wName . ' = :wh_' . $wName . ' ,';
}
//Trim last comma that was appended
$where_str = rtrim($where_str, ',');
//Set Query
$query = "UPDATE {$table} SET {$upd_string} WHERE $where_str";
$stmt = $this->conn->prepare($query);
//Exec
foreach ($fieldsVals as $k => &$v) {
$stmt->bindParam(":set_{$k}", $v);
}
foreach ($where as $k => &$v) {
$stmt->bindParam(":wh_{$k}", $v);
}
$stmt->execute();
return true;
}
The correct usage would be:
$stmt = $this->conn->prepare('UPDATE users SET session_key = :session WHERE username = :username');
$stmt->bindParam(':session', session_id(), PDO::PARAM_STR);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
Then execute.
I think your variable $fieldsVals is wrong due to the foreach's you do. Maybe you switching key und val by accident, resulting in WHERE admin=username.
Update:
#MarcinNabiaĆek is right of course you are missing quotes.
But it seems like the error is coming from a different part of the script.
It seems you don't use ' in your query in PHP. Either you don't use it or use other symbol that look similar.
If I run in phpmyAdmin query:
UPDATE users SET session_key = 1234567890 WHERE username = admin
I also get error message:
#1054 - Unknown column 'admin' in 'where clause'
but when I have
UPDATE users SET session_key = 1234567890 WHERE username = 'admin'
it works fine
In your code you should definitelly change:
$where_str .= "$wName = $wValue";
into
$where_str .= "$wName = '$wValue'";
session_key is a varchar
You have to use the query like the below,
$query = "UPDATE users SET session_key = '1234567890' WHERE username = 'admin'";
column admin doesn't exist! column administrator exists though.
I don't see any admin column in your mysql table in the screenshot that you provided.
You can simply change the name of the administrator column in your mysql table to admin and everything will work.
My script is quitting on SQL calls that should not have an issue. One of the queries that is failing to update is:
UPDATE dist_comp.private_schools SET mail_address = '1351 Royalty Dr', city = 'Alabaster', state = 'AL',zip_code = 35007,phone = '2056633973' WHERE school_name = 'Kingwood Christian School' AND city = 'Alabaster'
When I run the same query in MySQL workbench, I get
Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Queries and reconnect.
Is this the reason why my script is quitting?
<?php
require_once('connect.php');
function schoolInfo($school_name,$city){
$data = array();
$counter = 0;
$handle = fopen("k12privateschools_loc_0813.csv","r") or exit('doesnt work');
fgetcsv($handle) or exit('fgetcsv issue');
while( ($line = fgetcsv($handle)) !== false) {
$data[] = $line;
///echo ("Does schoolname and city match: " . addslashes($data[$counter][2]). ":" . $school_name . " ; " . addslashes($data[$counter][4]). ":" . $city . "\n");
if (addslashes($data[$counter][2])==$school_name && addslashes($data[$counter][4])==$city){
//echo ('match');
if($data[$counter][13] != ""){
$mail_address = $data[$counter][12];
$city= $data[$counter][13];
$state= $data[$counter][14];
$zip_code= $data[$counter][15];
$zip_4= $data[$counter][16];
}else{
$mail_address = $data[$counter][3];
$city= $data[$counter][4];
$state= $data[$counter][5];
$zip_code= $data[$counter][6];
$zip_4= $data[$counter][7];
}
$phone= $data[$counter][8];
$query= "UPDATE dist_comp.private_schools SET
mail_address = '".$mail_address."',
city = '".$city."',
state = '".$state."',";
if($zip_code != ""){
$query.="zip_code = ".$zip_code.",";
}
if($zip_4 != ""){
$query.="zip_4 = ".$zip_4.",";
}
$query.= "phone = '".$phone."'
WHERE school_name = '".$school_name."' AND city = '" .$city . "'";
mysqli_query($con,$query);
if(mysqli_affected_rows($con)==0){
exit($query . "\n ");
}
//echo $query;
}//end if counter \
else{
//echo("no match");
}
$counter++;
}//end read lines from file
}
echo "starting import \n";
//Query for all school names
$sql2 = mysqli_query($con,"SELECT school_name,city FROM dist_comp.private_schools") or exit('query issue second');
while($row = mysqli_fetch_array($sql2)){ //this line is making it take a really long time
$school_name= addslashes($row['school_name']);
$city = addslashes($row['city']);
schoolInfo($school_name,$city);
}//end while fetch array
//}
echo "Import finished";
?>
Try to disable safe update using this line before your query :
mysqli_query($con,"SET sql_safe_updates=0");
Or use :
$query="SET sql_safe_updates=0";
$query.= "UPDATE dist_comp.private_schools SET
mail_address = '".$mail_address."',
city = '".$city."',
state = '".$state."';";
mysqli_multi_query($con,$query);
or in MySQL WorkBench:
Edit -> Preferences -> SQL Queries
Uncheck Forbid UPDATE and DELETE statements without a WHERE clause
(safe updates)
Query --> Reconnect to Server
$query = 'SET SQL_SAFE_UPDATES=0;';
$query .= 'custom query here;';
$query .= 'SET SQL_SAFE_UPDATES=1;';