SQL without a WHERE that uses a key column - php

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;';

Related

Retrieve data from one table and insert/update in another table in mysql

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

PHP doesn't execute functions with sql correct

I will put my code below. I basically check on value in the database and if it's 1 or 0 i want to change it to the opposite (so if 1 change it to 0, if 0 change to 1).
If I execute one SQL statement without using the function (but then it only works one way once) it works. But if I want to execute the specific function with it depending on what the value currently is, it doesn't seem to work. Do you know what I am doing wrong here?
<?php
$date_id = $_POST['dateID'];
$con = mysqli_connect("localhost","root","","secret_name");
$sql = "SELECT * FROM date_list WHERE date_id = ".$dateID;
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
$occupied = $row['occupied'];
if($occupied == 1){
decross_entry();
} elseif( $occupied == 0){
cross_entry();
}else{
echo "Error"
}
}
function decross_entry(){
$dateID = $_POST['dateID'];
$con_2 = mysqli_connect("localhost","root","","secret_name");
$sql_edit = "UPDATE date_list SET occupied= '0' WHERE date_id = ".$dateID;
if($con_2 -> connect_errno){
echo "Failed to connect to database!" . $con_2->connect_error;
}
if ($con_2 -> query($sql_edit) === TRUE)
{
echo "saved!";
} else {
echo "error: " .$sql_edit."<br>".$con_2->error;
}
}
function cross_entry(){
$dateID = $_POST['dateID'];
$con_2 = mysqli_connect("localhost","root","","secret_name");
$sql_edit = "UPDATE date_list SET occupied= '1' WHERE date_id = ".$dateID;
if($con_2 -> connect_errno){
echo "Failed to connect to database!" . $con_2->connect_error;
}
if ($con_2 -> query($sql_edit) === TRUE)
{
echo "saved!";
} else {
echo "error: " .$sql_edit."<br>".$con_2->error;
}
}
?>
If the only possible values of occupied are 0 and 1 then you can do what you want in one query without needing to look up the value of occupied first:
UPDATE date_list
SET occupied = 1 - occupied
WHERE date_id = ?
In PHP, using a prepared query to avoid SQL injection:
$date_id = $_POST['dateID'];
$con = mysqli_connect("localhost","root","","secret_name");
$sql = "UPDATE date_list SET occupied = 1 - occupied WHERE date_id = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param('i', $date_id); // use 's' if $date_id is not an integer
$stmt->execute();

How to properly update a SQL table row using PHP

Current update: I've cleaned up the code, and there are still some issues.
NOTE this code runs every 3 seconds. The outermost 'else' statement seems to run, setting the time to 0 in the database table, but then there is no activity.
After the initial time of running, the outermost 'else' statement should never run, and the time value stored under the user's alias should keep updating with the latest time stamp, but it just sits at '0'.
This is the JS that runs the php file:
//CHECK FOR NEW CHAT MESSAGES
setInterval(function()
{
$.post("chat_update.php", function(data) { $("#rect_comments_text").append(data);} );
}, 3000);
Code:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$time_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$timestamp = time();
$last_time_query = "SELECT alias FROM $time_table";
$last_time_result = mysqli_query($connection,$last_time_query);
$last_time_rows = mysqli_fetch_array($last_time_result);
if ($last_time_rows['alias'] === $alias)
{
$last_time = $last_time_rows['time'];
$query = "SELECT * FROM $table WHERE time > $last_time ORDER BY text_id ASC"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
//APPEND NEW MESSAGES
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
}
//UPDATE LAST SYNC TIME
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
echo '<p> HERE </p>';
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','0')";
mysqli_query($connection,$update_query);
}
?>
You try this
$sql_update = "UPDATE time_table SET time= '$timestamp' WHERE alias = '$alias'";
if ($con->query($sql_update ) === TRUE) {
}
else{
echo "Error: " . $sql_update . "<br>" . $con->error;
}
You need to only check mysqli_num_rows to whether to insert or update data. You have to add ' around $alias in select query also. change your code as below:
//EITHER UPDATE THE EXISTING VALUE OR CREATE ONE FOR FIRST TIME VISITORS...
$last_time_query = "SELECT * FROM $time_table WHERE alias = '$alias'"; //change here add '
$last_time_result = mysqli_query($connection,$last_time_query);
if (mysqli_num_rows($last_time_result) == 0) //Only check number of rows
{
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','$timestamp')";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}

PHP MySql PDO Multiple insert doesn't work

I have this code for a multiple insert query (I have to transfer data from db to another and makes some update, so I wanna use a code that could do all this automatically)
$query = "select * from pubblicate order by idPubblicate asc";
$dbh = newPdo2();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query);
$sth->execute();
$count = 0;
$query2 = "insert into published_offer
(codice_onshop,nome,inbreve,anteprima,
galleria1,galleria2,galleria3,galleria4,prezzo,
tp_prezzo,bonus_usabile,proposta,condizioni,
prenotare,categoria,description,keywords,
valido_da,valido_a) ";
while($offerta = $sth->fetch(PDO::FETCH_ASSOC)) {
$array[$count]['id'] = $offerta['idPubblicate'];
$array[$count]['co'] = $offerta['codiceOfferta'];
$array[$count]['no'] = $offerta['nomeOfferta'];
$array[$count]['ib'] = $offerta['inBreve'];
$array[$count]['ke'] = $offerta['keywords'];
$array[$count]['de'] = $offerta['description'];
$array[$count]['pr'] = $pfferta['prezzo'];
$array[$count]['pe'] = $offerta['persona'];
$array[$count]['da'] = $offerta['daTimer'];
$array[$count]['a'] = $offerta['aTimer'];
$array[$count]['an'] = $offerta['anteprima'];
$array[$count]['g1'] = $offerta['galleria1'];
$array[$count]['g2'] = $offerta['galleria2'];
$array[$count]['g3'] = $offerta['galleria3'];
$array[$count]['g4'] = $offerta['galleria4'];
$array[$count]['pro'] = $offerta['proposta'];
$array[$count]['con'] = $offerta['condizioni'];
$array[$count]['pre'] = $offerta['prenotare'];
$array[$count]['bo'] = 999;
if($offerta['italia']=="Sì") $array[$count]['ca'] = "ita";
else if($offerta['europa']=="Sì") $array[$count]['ca'] = "eur";
else if($offerta['mondo']=="Sì") $array[$count]['ca'] = "mon";
$count++;
}
$query2 .= "values (:co,:no,:ib,:an,:g1,:g2,
:g3,:g4,:pr,:pe,:bo,:pro,:con,
:pre,:ca,:de,:ke,:da,:a)";
$dbh = newPdo();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query2);
$i=0;
echo $array[0]['no'] . " " . count($array) . " " . $array[125]['no'] . "<br>" . $query2 . "<br>";
while($i<count($array)) {
$sth->bindParam(":co", $array[$i]['co']);
$sth->bindParam(":no", $array[$i]['no']);
$sth->bindParam(":ib", $array[$i]['ib']);
$sth->bindParam(":an", $array[$i]['an']);
$sth->bindParam(":g1", $array[$i]['g1']);
$sth->bindParam(":g2", $array[$i]['g2']);
$sth->bindParam(":g3", $array[$i]['g3']);
$sth->bindParam(":g4", $array[$i]['g4']);
$sth->bindParam(":pr", $array[$i]['pr']);
$sth->bindParam(":pe", $array[$i]['pe']);
$sth->bindParam(":bo", $array[$i]['bo']);
$sth->bindParam(":pro",$array[$i]['pro']);
$sth->bindParam(":con",$array[$i]['con']);
$sth->bindParam(":pre",$array[$i]['pre']);
$sth->bindParam(":ca", $array[$i]['ca']);
$sth->bindParam(":de", $array[$i]['de']);
$sth->bindParam(":ke", $array[$i]['ke']);
$sth->bindParam(":da", $array[$i]['da']);
$sth->bindParam(":a", $array[$i]['a'] );
$sth->execute();
$i++;
}
But this code doesn't work. I've also tried to use try-catch(PDOException) for $sth->execute() but it doesn't show me anything.
Why?
Who says "this question is a duplicated" doesn't read really the question. Infact the error was a wrong character: $array[$count]['pr'] = $pfferta['prezzo'] would be been $array[$count]['pr'] = $offerta['prezzo']so I couldn't find an answer in another question.
Try adding some simple checks that things actually worked like this
$res = $sth->execute();
if ( ! $res ) {
echo sprintf('ERROR: %d - %s', $sth->errorCode(), $sth->errorInfo() );
}

Dynamic select query according to form fields

I have a form with two fields. The user can fill in either one or both and the MySQL database should be queried accordingly.
Here is my php code:
$number1 = $_POST['number1'];
$number2= $_POST['number2'];
$set = FALSE;
$query = "SELECT * FROM table";
if (!empty($number1 ))
{
$query .= " WHERE number1 = ".$number1."";
$set = TRUE;
}
if (!empty($number2))
{
$query .= ($set===TRUE ? " AND" : " WHERE") . " number2 = ".$number2."";
}
$data = mysql_query($query) or die("Couldn't execute query. ". mysql_error());
The code works fine if either number1 or both of the fields are filled in. However when only the second field is filled in I get the error:
Couldn't execute query. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
If I echo the query it is shown correctly:
SELECT * FROM table WHERE number2 = entered value
Any help is much appreciated! Thanks!!
have you forget escape values? u can use somthing like this
$fields = array();
if(!empty($_POST['number1'])) {
$fields[] = 'number1='.mysqli_real_escape_string($_POST['number1']);
}
if(!empty($_POST['number2'])) {
$fields[] = 'number2='.mysqli_real_escape_string($_POST['number2']);
}
$sql = "SELECT * FROM table WHERE ".implide(" AND ", $fields);
$data = mysqli_query($query) or die("Couldn't execute query. ". mysql_error());
mysql extension is deprecated, use mysqli instead
try this
$number1 = $_POST['number1'];
$number2= $_POST['number2'];
$set = FALSE;
$query = "SELECT * FROM table";
if (!empty($number1 ))
{
$query .= " WHERE number1 = ".$number1."";
$set = TRUE;
}
if (!empty($number2))
{
if($set==FALSE)
$query .= " WHERE number2 = ".$number2;
else
$query .= " AND number2 = ".$number2;
}
I think you get the error because of the assignment. You wrote $set===TRUE, its == not ===
The error is here:
if (!empty($number2))
{
$query .= ($set===TRUE ? " AND" : " WHERE") . " number2 = ".$number2."";
}

Categories