Private message values not inserting - function

I'm having trouble inserting my values from one page into another and then into the database its showing no errors either which is rather puzzling and not inserting into the database.
I pass the values over from a form via ajax and all the values needed are being sent over so I presume it has something to do with the values sent over from pminsert. Database is included and all my values are safe from sql injection. I've just put the needed code below.
pminsert
if($_POST['pmtoid']==$_SESSION['id']){
user_core::pmmessage("1",$_POST['pmfromid'],$_POST['pmtoid'],$_POST['pmnewmsg'],"../pm.php?id=".$_POST['pmtoid']."&id2=".$_POST['pmfromid']."",$date);
}else{
user_core::pmmessage("3",$_POST['pmfromid'],$_POST['pmtoid'],$_POST['pmnewmsg'],"../pm.php?id=".$_POST['pmfromid']."&id2=".$_POST['pmtoid']."",$date);
}
user_core::pmmessage
public function pmmessage($typeids,$creatorids,$targetusers,$contents,$url,$date){
global $mysqli;
$contents = $contents;
//$content = strip_tags($content);
if($contents>0){
$date=date('y:m:d H:i:s');
$insertmessage = "INSERT INTO messages(message_type_id,message_creator,message_target,message_content,message_throughurl,message_time) VALUES ($typeids,$creatorids,$targetusers,$contents,$url,$date)";
$add_message = mysqli_query($mysqli,$insertmessage)or die(mysqli_error($mysqli,$insertmessage));

Make sure auto-commit was enabled, else don't forget to commit or you'll never see your data updated. That would explain why there is no errors.

Related

Placing PHP variable inside SQL

I am trying to send city from a page to another and then show items from database where city is the mentioned city but this code does not return any results. Please guide. I am sure everything else is fine with the code.
$city = $_POST["city"];
$sql = "SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city=$city";
// strip tags from the input
$city = strip_tags($_POST["city"]);
// escape the input to prevent sql injection (assuming you are using mysqli() as your connection method...)
$city = mysqli_real_escape_string($city);
// your query does not work because you need to put strings inside single quotes
$sql = "SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city='$city'";
Actually, you're not even executing the request on your mysql server, but if you are using PDO (what you SHOULD do), just do something like this:
<?php
$bdd = new PDO(etc);
$req = $bdd->prepare("SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city=?");
$req->execute(array($_POST['city']));
print_r($req->fetchAll());
?>
And here you go, $req->fetchAll() will return you an array with each element returned by your request, and the best part is that prepare will prevent you from every SQLi
Edit: You can use short syntax for array [$_POST['city']] or old and complete syntax: array($_POST['city'])

PDO Sql query not working

I am using the following code to insert in MYSQL table:
try{
$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES(':t_id',':t_name',':mem_id')";
$stmt=db::con()->prepare($sql);
$stmt->bindParam(':t_id',$tid,PDO::PARAM_INT);
$stmt->bindParam(':t_name',$tNm,PDO::PARAM_STR);
$stmt->bindParam(':mem_id',$mId,PDO::PARAM_INT);
$stmt->execute();
}catch(PDOException $ex){
die("Error occured:".$ex->getMessage());
}
$tid variable has value=1;
$tNm variable has value='CBSE';
$mId variable has value=9
when this piece of code is run then no error is generated but in MYSQL table i observe the field values as 't_id'=0, 't_name'=t_name, 'mem_id'=0.I just don't understand what is wrong with my code.However, one funny thing is that when i try to acomplish the same task using the below mentioned code, proper data is inserted into the table.The code is
$db= new Database();
$db->open();
$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES('$tid','$tNm','$mId')";
$db->query($sql);
When using PDO to bind parameters, keep in mind that it appropriately quotes and escapes for you automatically. This means you need to remove the quotes from your VALUES statement, as follows:
$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES(:t_id,:t_name,:mem_id)";

Updating user profile efficiently

Something just came to mind and I'd like to bounce it off:
Say you have a user profile, with 10 fields that the user can edit, and not all of them are required. When issuing update commands, is it more efficient to either:
A) Collect all of the fields, filled in or not, and issue one all encompassing update statement to the server's DB
or
B) Use client side validation to check to see which fields have been filled out or changed, and have a selection of SQL methods that only send and update these fields
or
C) Create groupings, like "updateRequiredFields(...) and updateExtraFields(...)", which would issue one smaller transfer if the changes only belong in one group, however two transfers if both are edited
General consensus? Clearly option B is the far more verbose approach, I'm just wondering if it's worth coding it all out or if it'll actually make a noticeable impact on the server (think "scaled for big data").
You could do something like this on your DB update function:
public function updateFields(array $fields) {
$updateQuery = array();
foreach($fields as $fieldKey => $fieldValue) {
//if $fieldValue is false, leave it unchanged
if ($fieldValue !== false) {
//NOTE: make sure you escape this or use PDO
$updateQuery[] = $fieldKey . '=' . $fieldValue;
}
}
$query = 'UPDATE UserInfo SET ' . implode(",", $updateQuery) . ' WHERE ...';
}
You just need to build $fields array based on what was modified on client side and then pass in with either new value or with false if no change.

MYSQL?PHP using variables to replace filenames in insert statements

I have a page that inserts records into a database file called ports that holds two fields, called id and port.
The data is checked by an include, checkform.php, that strips out any bad data and blank entries.
It works fine, and as I have more data files of a similar construction it seems logical to use the same page for inserting records by passing the file and field names to the page as parameters.
The SQL that is used for the stand alone page is:
$sql='INSERT IGNORE INTO ports(port) VALUES(?)';
I want to do some thing like:
$sql='INSERT IGNORE INTO $filename ($fieldname) VALUES(?)';
I have looked on the forum and found many solutions that do not appear to work
Like :
$sql='INSERT IGNORE INTO '$filename' ('$fieldname') VALUES(?)';
$sql='INSERT IGNORE INTO "'$filename'" ("'$fieldname'") VALUES(?)';
$sql='INSERT IGNORE INTO `$filename` (`$fieldname`) VALUES(?)';
as well as :
$sql="INSERT IGNORE INTO `$filename` (`$fieldname`) VALUES (`$fieldname`);";
and many others. The combination seems endless, and so far I would have been better just copying the pages and changing the variables by hand. The code for the insert is below:
// check if form submitted and has a value
If (isset($_POST['insert']))
{ require('../includes/checkform.inc.php');
// continue if the field is OK
if (empty($missing)) // ** missing is empty if the data is clean and exists
{ // process the input.
require_once('../includes/connection.inc.php');
// initialize a flag
$OK = false;
//create database connection
$conn = mysqli_connect( $DatabaseServer,$DatabaseUser, $DatabasePassword, $DatabaseName);
// Initialize prepared statement
$stmt = $conn->stmt_init();
//create SQL
$sql='INSERT IGNORE INTO ports(port) VALUES(?)'; //#
//bind parameters and execute statement
if($stmt->prepare($sql)) {
$stmt->bind_param('s',$_POST['port']);//#
$stmt->execute();
if ($stmt->affected_rows > 0)
$OK = true;
}//if $tmt
}// if empty
// redirect if successful or display an error - on page below
if ($OK) {
header('Location:insertok.php');
exit;
} else {
$error = htmlspecialchars($stmt->error);
The lines with //# against them are the ones that I need help with.
Most of the code is modified from a book by David Powers.
Howard Walker
To interpolate variables in a string, you have to use double quotes "$var". Note that you shouldn't surround $var with single quotes. And your table and column names might be one of the reserved words. It complains when that happens. You use backticks to escape the reserved words.
$sql="INSERT IGNORE INTO `$filename` (`$fieldname`) VALUES (?);";
This should work just fine.
EDIT
Your file/field might also include the characters that mySQL doesn't like. In that case, escape the query string before executing it. Refer: http://us3.php.net/manual/en/mysqli.real-escape-string.php
$sql = $stmt->real_escape_string($sql);

Prepared statement fetches all the results in db, but not one I ask for

Trying to make my blog secure and learning prepared statements.
Although I set the variable, I still get all the entries from database. $escapedGet is real variable when I print it out. It's obviously a rookie mistake, but I cant seem to find an answer.
I need to get the data where postlink is $escapedGet not all the data.
$escapedGet = mysql_real_escape_string($_GET['article']);
// Create statement object
$stmt = $con->stmt_init();
// Create a prepared statement
if($stmt->prepare("SELECT `title`, `description`, `keywords` FROM `post` WHERE `postlink` = ?")) {
// Bind your variable to replace the ?
$stmt->bind_param('i', $postlink);
// Set your variable
$postlink = $escapedGet;
// Execute query
$stmt->execute();
$stmt->bind_result($articleTitle, $articleDescription, $articleKeywords);
while($stmt->fetch()) {
echo $articleTitle, $articleDescription, $articleKeywords;
}
// Close statement object
$stmt->close();
}
just tryed this: echo $escapedGet;
echo $_Get['artcile']
and got - some_other
thats the same entry that I have saved in database as postlink
tried to shande postlink to id, and then it worked. but why not with postlink tab?
When you are binding your data using 'i' modifier, it gets bound as integer.
Means string will be cast to 0 in the final statement.
But as mysql does type casting, your strings become zeroes in this query:
SELECT title FROM post WHERE postlink = 0;
try it and see - for the textual postlinks you will have all your records returned (as well as a bunch of warnings).
So, bind strings using s modifier, not i