Thanks in advance for everyone's help. I have an issue that has driven me crazy for hours. I've tried writing this several times using several methods with full error checking. I've tried single quotes on the field names, I've tried putting an SQL query in a variable and passing it to $db->prepare -- all to no avail. I've checked my permissions and everything looks good to me. I'm sure it's something simple but I'm bleary-eyed going over this and I'm just not seeing it.
$db = OpenDBConn();
// $query = "UPDATE agent_profiles SET ";
// $query .= "website = ?, display_email = ?, primary_phone = ?, secondary_phone = ?, secondary_phone_type = ?, ";
// $query .= "address_1 = ?, address_2 = ?, city = ?, state = ?, zip = ?, country = ?, description = ? ";
// $query .= "WHERE agent_id = ?";
$stmt = $db->prepare("UPDATE agent_profiles SET
website=?,
display_email=?,
primary_phone=?,
secondary_phone=?,
secondary_phone_type=?,
address_1=?,
address_2=?,
city=?,
state=?,
zip=?,
country=?,
description=?
WHERE agent_id=?");
$stmt->bind_param('ssssssssssssi', $this->website, $this->display_email, $this->primary_phone, $this->secondary_phone, $this->secondary_phone_type, $this->address_1, $this->address_2, $this->city, $this->state, $this->zip, $this->country, $this->description, $this->agent_id);
$stmt->execute();
$stmt->close();
$db->close();
Even with full error reporting and modifying the code to look for $db->error, it all looks and runs clean but doesn't save to the table. Functions used here are used in other places and work fine. Any guesses?
error_reporting(-1);
ini_set('display_errors', 'On');
Is your friend, why do you always exclude him on your journeys?
Related
I have the following in my PHP.
$stmt = $conn->prepare("INSERT IGNORE INTO savesearch (user, searchedFor, sortOrder, buildURLString, aspectFilters, oneSignalId, totalEntries)
VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $user, $searchedFor, $sortOrder, $buildURLString, $aspectFilters, $oneSignalId, $totalEntries);
// set parameters and execute
$user = $_POST['user'];
$searchedFor = $_POST["searchedFor"];
$sortOrder = $_POST["sortOrder"];
$buildURLString = $_POST["buildURLString"];
$aspectFilters = $_POST["aspectFilters"];
$oneSignalId = $_POST["oneSignalId"];
$totalEntries = $_POST["totalEntries"];
if ($stmt->execute()) {
$output->success = true;
echo json_encode($output);
} else {
$error->error = mysqli_error($conn);
echo json_encode($error);
}
However, IGNORE is not being picked up, it continues to add entries. Is there another good way to fix this?
Id like to see if the USER and the URL is the same, dont add, echo duplicate entry.
IGNORE is actually mostly for the opposite of what you want here. Instead, you can amend your MySQL table something like:
ALTER TABLE savesearch ADD UNIQUE KEY(user, buildURLString)
Then remove your IGNORE keyword
Please How can i use prepared statement to update one table and insert into another table. i did what i no was right but the when i submit the form on that page, it just give me a blank page and nothing happened in the two database see what it look like
$check = "INSERT INTO users(userEmail, password, joinDate, recEmails,
isActive, hash, lastUpdated)
VALUES (?, ?, NOW(), 1, 0, ?, NOW() ) ";
$stmt = $mysqli->prepare($check);
$stmt->bind_param('sss',$emailAddy,$password,$hash );
$stmt->execute();
$stmt->close();
$check1="UPDATE pin SET status = '1', usedby = ?,WHERE pin = ?";
$stmt = $mysqli->prepare($check1);
$stmt->bind_param('ss',$emailAddy,$pin);
$stmt->execute();
$stmt->close();
The result i get is this example.com is currently unable to handle this request.
I have tried and discovered that the issue is hidden somewhere here, if i remove the update table instruction the code works fine but one i return the issue comes back. Please can anybody help?
You have an error here:
$check1 = "UPDATE pin SET status = '1', usedby = ?, WHERE pin = ?";
Change it to (Remove the , after usedby = ?)
$check1 = "UPDATE pin SET status = '1', usedby = ? WHERE pin = ?";
So I've been trying to find an answer but I don't think there is one that is specified to what I am trying to do. I will start with my sample of code
file.php
$q = "INSERT INTO ".PORTAL_DB.".resource_file (company__id, rf_category__id, title, file_name, description, path, upload_by, has_quiz)
SELECT ?, ?, ?, CONCAT(MAX(id)+1, '.', '$extension'), ?, ?, ?, ? FROM ".PORTAL_DB.".resource_file";
$stmt = $CONN->prepare($q);
$filename = 0;
$resource_file__id = 0;
if($stmt->execute(array($company__id, $rf_category__id, $title, $description, "assets/$uploadFolder/", USER, $has_quiz))){
$filename = $CONN->lastInsertId();
$resource_file__id = $filename;
}
if(!empty($quiz)){
$passing_score = $quiz->passing_score;
if(!is_numeric($passing_score) or ($passing_score < 0) or $passing_score > 100){
$CONN->rollback();
throw new Exception("Invalid passing score value for quiz, please fix");
}
$q = "INSERT INTO ".PORTAL_DB.".rf_quiz (resource_file__id, passing_score)
VALUES(?, ?)";
$stmt = $CONN->prepare($q);
$rf_quiz__id = 0;
$stmt->execute(array($resource_file__id, $passing_score));
print_r($CONN->lastInsertId);
exit;
$question_ids = array();
foreach($quiz as $qz){
$question = $qz->question;
//print_r($qz);
$q = "INSERT INTO ".PORTAL_DB.".rf_quiz_question (rf_quiz__id, question)
VALUES(?, ?)";
$stmt = $CONN->prepare($q);
if($stmt->execute(array($rf_quiz__id, $question))){
array_push($question_ids, $CONN->lastInsertId);
}
}
//print_r($question_ids);
exit; // using this for testing only
}
explanation
The above code is called after $CONN->beginTransaction() so that I can manage errors easier. From what I understand you can call the stamtement $CONN->lastInsertId() multiple times without issue, however I can get the first id which is stored under the variable $resource_fild__id then when we go down to the $rf_quiz__id variable, even if the call is successful, I get nothing and it causes an error. I want to be able to do all of this in one transaction for the ease of the coding process and organization.
I hope someone can point me in the right direction, or at least be able to tell me what I am doing wrong so that I can find a fast solution!
Thank you for all help in advance.
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I'm currently using the following insert query to update values in mysql using php:
$UpdateQuery = "UPDATE `mysqldb`.`cu_data` SET
`app_status` = '".$_POST['Est']."',
`nacionalidad` = '".$_POST['Nac']."',
`ciudad_ini` = '".$_POST['CiudadI']."',
`ciudad_ent` = '".$_POST['CiudadE']."',
`ciudad_dest` = '".$_POST['CiudadD']."',
`ciudad_land` = '".$_POST['PEntrada']."',
`uso_consr` = '".$_POST['U_Abog']."',
`start` = '".$_POST['Envi']."',
`t1` = '".$_POST['Cob']."',
`t2` = '".$_POST['Acus']."',
`t3` = '".$_POST['Invit']."',
`t4` = '".$_POST['Entre']."',
`t5` = '".$_POST['Recibo']."',
`t6` = '".$_POST['EnvioF)']."',
`t7` = '".$_POST['DatInternet']."',
`t8` = '".$_POST['SoliMed']."',
`t9` = '".$_POST['OrdeMe']."',
`t10` = '".$_POST['SoliciPasa']."',
`t11` = '".$_POST['EnvioPasas']."',
`t12` = '".$_POST['RecepPasa']."',
`end` = '".$_POST['Landing']."',
`Notas` = '".$_POST['Notas']."',
`LastChange` = NOW()
WHERE `cu_data`.`procid` = '".$_POST['Proceso']."' AND
`cu_data`.`userid` = '$userid'
";
$result = mysqli_query($con, $UpdateQuery);
The code is working, but now I'm worried about sql inyections (not only the bad kind, but also things like the user including a semi-colon in any of the form fields)
I was thinking using some kind of escaping using mysql_real_escape_string (as suggested in the sencond most voted answer to this question), but then I see some pitfalls in the comments (and I'm having a hard time understanding the most voted one).
any tips?
thanks in advance
Ps: At least for the last field (notas) I need the user to enter any symbols such as ($ # % ; : ,.>
Edited:
I did look at the suggested answer (sorry I had a bad like to another SO answer in the original question). So, as not to be duplicate, could I ask for a clue on on how to do the PDO thing to a update query like the one I'm showing above? (My php is from the mysql_ days!)
Edited (2):
Ok, so this question has been flagged as duplicate, yet I don't agree with the selected answer (the one that shows after This question already has an answer here: as that's the one I read before asking this question. I did found another one that looks more interesting (at least to me) here: Replacing mysql_* functions with PDO and prepared statements (of course this one starts to make sense once one is aware of PHP Data Objects, aka PDO, which I wasn't
Edited (3):
Well I got this to work as follow:
$UpdateQuery1 = "UPDATE `mysqldb`.`cu_data` SET
`app_status` = ?,
`nacionalidad` = ?,
`ciudad_ini` = ?,
`ciudad_ent` = ?,
`ciudad_dest` = ?,
`ciudad_land` = ?,
`uso_consr` = ?,
`start` = ?,
`t1` = ?,
`t2` = ?,
`t3` = ?,
`t4` = ?,
`t5` = ?,
`t6` = ?,
`t7` = ?,
`t8` = ?,
`t9` = ?,
`t10` = ?,
`t11` = ?,
`t12` = ?,
`end` = ?,
`Notas` = ?,
`LastChange` = NOW()
WHERE `cu_data`.`procid` = ? AND
`cu_data`.`userid` = ?";
$stmt = $con->prepare($UpdateQuery1);
$stmt->bind_param('ssssssssssssssssssssssss',
$_POST['Estatus'],$_POST['Nacionalidad'],$_POST['CiudadI'],$_POST['CiudadE'],$_POST['CiudadD'],
$_POST['PEntrada'],$_POST['Uso_Abog'],$_POST['Envi'],$_POST['Cobro_de_Fee'],
$_POST['Acus'],$_POST['Invit'],$_POST['Entre'],$_POST['Recibo'],$_POST['EnvioF'],
$_POST['DatInternet'],$_POST['SoliMed'],$_POST['OrdeMe'],$_POST['SoliciPasa'],
$_POST['EnvioPasa'],$_POST['RecepPasa'],$_POST['Landing'],$_POST['Notas'],
$_POST['Proceso'],$userid);
$stmt->execute();
As a bonus, my field Notas seems to be able to hold any text, without having to escape special character
For best protection against injection attacks, use mysqli or PDO and prepared statements. Mysql_* functions are deprecated. Info on mysqli can be found in the documentation.
For example, a query with prepared statements looks like this:
$stmt = $mysqli->prepare('SELECT lastname FROM customers WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt -> bind_result($lastName);
$stmt -> fetch();
The $id holds the string to be escaped, and the $lastName variable will hold the value returned from the database. This will prevent sql injection attacks.
I was wondering if someone could help me.
Im trying to integrate some code into my application, the code that i need to integrate is written with PDO statements and i have no idea how it goes.
I was wondering if someone could help me convert it.
The code is as follows
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
$stmt = $PDO->prepare($sql);
$stmt->execute($args);
if (empty($mid)) {
$mid = $PDO->lastInsertId();
}
$insertSql = "insert into message2_recips values ";
$holders = array();
$params = array();
foreach ($rows as $row) {
$holders[] = "(?, ?, ?, ?)";
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
$insertSql .= implode(',', $holders);
$stmt = $PDO->prepare($insertSql);
$stmt->execute($params);
You shoudl use PDO unles for some technical reason you cant. If you dont know it, learn it. Maybe this will get you started:
/*
This the actual SQL query the "?" will be replaced with the values, and escaped accordingly
- ie. you dont need to use the equiv of mysql_real_escape_string - its going to do it
autmatically
*/
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
// these are the values that will replace the ?
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
// create a prepared statement object
$stmt = $PDO->prepare($sql);
// execute the statement with $args passed in to be used in place of the ?
// so the final query looks something like:
// insert into message2 (mid, seq, created_on_ip, created_by, body) values ($mid, $seq, 1.2.2.1, $currentUser, $body)
$stmt->execute($args);
if (empty($mid)) {
// $mid id is the value of the primary key for the last insert
$mid = $PDO->lastInsertId();
}
// create the first part of another query
$insertSql = "insert into message2_recips values ";
// an array for placeholders - ie. ? in the unprepared sql string
$holders = array();
// array for the params we will pass in as values to be substituted for the ?
$params = array();
// im not sure what the $rows are, but it looks like what we will do is loop
// over a recordset of related rows and do additional inserts based upon them
foreach ($rows as $row) {
// add a place holder string for this row
$holders[] = "(?, ?, ?, ?)";
// assign params
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
// modify the query string to have additional place holders
// so if we have 3 rows the query will look like this:
// insert into message2_recips values (?, ?, ?, ?),(?, ?, ?, ?),(?, ?, ?, ?)
$insertSql .= implode(',', $holders);
// create a prepared statment
$stmt = $PDO->prepare($insertSql);
// execute the statement with the params
$stmt->execute($params);
PDO really is better. It has the same functionality as MySQLi but with a consistent interface across DB drivers (ie. as long as your SQL is compliant with a different database you can theoretically use the exact same php code with mysql, sqlite, postresql, etc.) AND much better parameter binding for prepared statements. Since you shouldnt be using the mysql extension any way, and MySQLi is more cumbersome to work with than PDO its really a no-brainer unless you specifically have to support an older version of PHP.