Can't save php variable to mysql database or to file - php

I have a problem. I can't save my array data to database, i don't know why.
I try some version:
ver1:
$data=$_SESSION['need_save_data'];
$sql = "INSERT INTO session_search_data (`user_id`,`data`,`date`) VALUES ('" . $_SESSION['web_page_user_data']['id'] . "'," . $db_handler->db->quote(json_encode($data)) . ",'" . time() . "')";
$db_handler->db->query($sql);
and it save the database: []
if i echo my query, and run it in mysql console, it working fine:
INSERT INTO session_search_data (`user_id`,`data`,`date`) VALUES ('8','{\"selected_manufacturer_id\":\"504\"}','1442571431')
I try save the database json_encode, the result is similar, it save empty variable.
Also i try to save to file:
$data=$_SESSION['need_save_data'];
$filename = 'session_data/' . $_SESSION['web_page_user_data']['id'] . '.php';
$file = fopen($filename, "w");
fwrite($file, serialize($data));
I try save with json_encode, var_export, serialize, the result is: save empty variable data.
I use PHP 5.4 last version, i think it is configuration problem, because my code works fine two other servers, and my localhost.

Even if you are calling $db_handler->db->quote method, it will add quotes to the json encoded data only. You must wrap the data with quotes as well:
$sql = "INSERT INTO session_search_data (`user_id`,`data`,`date`)
VALUES ('" . $_SESSION['web_page_user_data']['id'] . "','" . $db_handler->db->quote(json_encode($data)) . "','" . time() . "')";
If this is not the problem then please verify that you are starting the session before trying to access session variables:
<?php
session_start();
Also, make sure you actually have some data inside the $_SESSION['need_save_data'] variable

make sure you're running in error_reporting(E_ALL), and make sure that query is successfully executed (if its PDO, make PDO run in PDO::ERRMODE->PDO::ERRMODE_EXCEPTION ), and make sure your fwrite succeeed, like
if(strlen(serialize($data))!==fwrite($file, serialize($data) || !fflush($file)){
throw new Exception("failed to write data to disk!");
}
then im sure the problem will become obvious... maybe you have a full harddrive? :p

so why you are trying to insert json into database when you can use explode? use prepared statements to avoid sql injection:
$uid = 8;
$data = $_SESSION['need_save_data']; // content: selected_manufacturer_id:504
$date = time();
$sql = "INSERT INTO `session_search_data` SET `user_id`=?, `data`=?, `date`=?";
if ($query = $dbcon->prepare($sql)) {
$query->bind_param('isi', $uid, $data, $date);
$query->execute();
$query->close();
}
so to retrieve the data from database and transform to json you can do:
$contents = explode(':', $data);
$transform = array();
$transform[$contents[0]] = $contents[1];
$to_json = json_encode($transform); // {"selected_manufacturer_id":"504"}

Related

My unique Id in form with multiple inputs can't be saved in my database Php

:) So i want to make a form with multiple inputs that are stored in the database with a unique id for every single input. My prblem is that if I save only one dynamic input the unique id is saved to my database but if i try for more than one it cant be saved. I tried many things but it dosent working. Can samone help.
PHP code
$values=array();
for($i=0 ;$i < count($_POST['fields']); $i++) {
$supply_unique_id=uniqid();
$values[] = '("' . $_POST['fields'][$i] . '","' . $supply_unique_id . '")';
}
$sql="INSERT INTO supplies (supply,supply_unique_id)
VALUES " . implode(',', $values);
$result = $conn->query($sql);
The problem was coming from uniqid() function it was duplicating the entry for key 'supply_unique_id' so I changed it to uniqid(rand(), true). It also works with md5() function. So this is the only thing I changed $supply_unique_id=uniqid(rand(), true);

Escaping for insert to MySql

I have a php page that uses mysql_real_escape_string() to escape content that contains single quotes. I believe it is using utf-8 (but I am not sure). When I insert some content, I get the following mysql warning (and it adds a ? instead of ' in the content):
Incorrect string value: '\x92t ...
Here is an example of my php:
$link = ConnectToServer($theIntranet, $theUser, $thePW);
$theTagToFind = 'ac';
$theTagToUse = 'trc';
$database = '{databaseName}';
$theQuery = "SELECT * FROM {$database}.templates
WHERE content like '%{" . $theTagToFind . ":%'";
$updates = fopen('001_intranet_change' . strtoupper($theTagToFind) . 'to' . strtoupper($theTagToUse) . '.sql', 'w+');
$rollback = fopen('001_intranet_change' . strtoupper($theTagToUse) . 'backto' . strtoupper($theTagToFind) . '.sql', 'w+');
$theResultHandle = mysql_query($theQuery, $link);
$comment = "--Update All $theTagToFind tags to $theTagToUse tags in $database --";
fwrite($updates, $comment . "\r\n\r\n");
fwrite($rollback, "--Rollback - Convert all $theTagToUse tags back to $theTagToFind tags --\r\n\r\n");
mysql_set_charset('latin1');
while (($data = mysql_fetch_assoc($theResultHandle)) != false)
{
$rb_content = $data['content'];
$data['content'] = preg_replace("/{" . $theTagToFind . ":/", "{" . $theTagToUse . ":", $data['content']);
$theResult[] = $data;
$update_script = "\r\n
Update $database.templates
SET content = '" . mysql_real_escape_string($data['content']) . "'
WHERE _id = " .$data['_id'] . ";";
$rollback_script = "\r\n
UPDATE $database.templates
SET content = '" . mysql_real_escape_string($rb_content) . "'
WHERE _id = " . $data['_id'] . ";";;
fwrite($updates, $update_script);
fwrite($rollback, $rollback_script);
}
fclose ($updates);
fclose($rollback);
print_r($theResult);
and $data['content'] could equal something like:
"Hello,
Please remember to contact the doctor's office at......"
here you go
mysql_set_charset('utf8');
you have to be sure that charset in your table definition also set to utf8
Are you sure your server is configured correctly and magic quotes are turned off? These can have the effect of double escaping values.
You can test this by looking at the $_POST data to see if it's been modified from what you'd expect. If so, see if you can fix the setting in php.ini.
As a note, you should not be using mysql_query in new code. It's dangerous, deprecated, and will be removed in future versions of PHP. Using SQL placeholders is the safest and easiest way to do escaping.
In your short example here it looks like you've forgotten to escape $data['_id'] which means it's a possible SQL injection bug. Even one mistake can have severe consequences, so never, ever put unescaped data into a query string.

Insert statement with CodeIgniter -- so confused

I'm doing well with CodeIgniter. I can do SELECT statements on my MySQL database with no problems at all. But, now I'm trying to do an INSERT statement.
Note that I have not tried an UPDATE statement yet.
After reading the docs, I'm so confused.
This is what I have:
contacts.php:
function add() {
//echo "<pre>";print_r($_POST);
$this->load->model('Contacts_model');
$this->Contacts_model->insertContact($_POST);
}
contacts_model.php:
function insertContact($_POST) {
//echo "<pre>";print_r($_POST);
$title = $_POST['title']; // I can echo this here. It works
$f_name = $_POST['f_name']; // I can echo this here. It works
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES (" .
$this->db->escape($title) .
"," .
$this->db->escape($f_name) .
")";
$this->$db->query($sql);
}
I've read about Active Record, but if that's what is messing me up, then I still don't realize what I'm doing wrong. All of the examples look exactly like mine.
Help?
EDIT
$sql = "INSERT INTO contacts (title,f_name) VALUES ('$this->db->escape($title)','$this->db->escape($f_name)'";
$this->$db->query($sql);
I've also tried it like this. And many other variants. It doesn't seem to be my syntax... I think.
Your query is fine, only reason that why query is not being executed is that you are using this:
$this->$db->query($sql);
there is nothing like $db, just use this:
$this->db->query($sql);
I'm sure this is the problem, but if it is not then please kindly post the error what it is giving. Thanks.
Hope this helps.
You missed the quote character:
$title = $this->db->escape($title);
$fname = $this->db->escape($f_name)
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES ('{$title}', '{$fname}')";
$this->db->query($sql);
BTW, What the hell with the $_POST variable? It's one of SuperGlobal variable. You don't have to transfer it in parameter. You can always safely call it anywhere in your script.
Another note, since you use CodeIgniter, you better check out the Input class library and use it for all your input need.
Why send $_POST? Use $this->input->post("param_name") and in your instance "$this->load->model('Contacts_model');" in my practice i use "$this->load->model('Contacts_model','instance',[true or false]);" the last parameter is optional (to connect with the DB if you don't use autoload option).
Use this:
function insertContact() {
$title = $this->input->post("title");
$f_name = $this->input->post("f_name");
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES ('" . $this->db->escape($title) . "','".$this->db->escape($f_name) ."')";
$this->$db->query($sql);
}
DON'T USE $_POST! (And use the Active Record read the user guide)

What are "Resource#'s"?

HI
I am getting Resource#6 and Resource#7 when I print the following variables:
$salty_password = sha1($row['salt'], $_POST['password']);
if(isset($_POST['subSignIn']) && !empty($_POST['email']) && !empty($_POST['password'])) {
$query = "SELECT `salt` FROM `cysticUsers` WHERE `Email` = '" . $_POST['email'] . "'";
$request = mysql_query($query,$connection) or die(mysql_error());
$result = mysql_fetch_array($request);
$query2 = "SELECT * FROM `cysticUsers` WHERE `Email` = '". $_POST['email']."' AND `Password` = '$salty_password'";
$request2 = mysql_query($query2,$connection) or die(mysql_error());
$result = mysql_fetch_array($request2);
print_r($request);
print_r($request2);
if(#mysql_num_rows($request,$request2)) {
$_SESSION['CLIFE']['AUTH'] = true;
$_SESSION['CLIFE']['ID'] = $result['id'];
// UPDATE LAST ACTIVITY FOR USER
$query = "UPDATE `cysticUsers` SET `LastActivity` = '" . date("Y-m-d") . " " . date("g:i:s") . "' WHERE `id` = '" . mysql_real_escape_string($_SESSION['CLIFE']['ID']) . "' LIMIT 1";
mysql_query($query,$connection);
if(!empty($_POST['return'])) {
header("Location: " . $_POST['return']);
}else{
header("Location: CysticLife-Dashboard.php?id=" . $_SESSION['CLIFE']['ID']);
}
}
}else{
$_SESSION['CLIFE']['AUTH'] = false;
$_SESSION['CLIFE']['ID'] = false;
}
?>
Trying to troubleshoot this code chunk and not sure what that means. I am trying to sign back in with the clear text password I signed up with after its been hashed and salted. I feel like I'm very close but something is slightly wrong. Help on why that is not working would be greatly appreciated as well.
Thanks in advance
mysql_query() returns result sets as objects of type resource (they're not objects in terms of PHP OOP code but I can't think of a better word). These contain binary data that can only be read by certain functions, for example the mysql_fetch_*() functions.
To debug your MySQL queries you should check for errors using mysql_error() and mysql_errno() and/or save your SQL statements in variables and print those.
From what I see, you're performing two queries but overwriting the same $result variable, without doing anything about the first. Also, mysql_num_rows() can only count one result set at a time, so you can't pass two result sets into the same call.
Those are PHP's internal data types called resource.
They cannot be serialized (i.e. there's no "toString()") and are hence displayed as Resource#X.
SQL queries through PHP are done using a variable known as a resource. This variable, in your code, is completely useless other than to pass to each function you want to perform (i.e. change a database, execute a query, grab the last error, etc.).
That being said, executing a query doesn't return any information from the database, just a reference to that record set (where in PHP it's storing the information). You would then use that variable in a call such as mysql_fetch_array to retrieve the actual row information.

Php Multi-Dimensional Array / MySql problem

I am trying to write a php script that take a text file break down its contents and and insert it into a MySql database, the code is as follows:
$file = "my_file.txt";
$db = "db_name";
$link = mysql_connect("localhost","root");
if(!$link) die("Connection Failed");
mysql_select_db($db) or die("Could not open $db: ".mysql_error()."<br />");
$fp = fopen($file, 'r') or die("Could not open file");
$my_filesize = filesize($file);
while(!feof($fp)) {
$prod_doc.=fread($fp, $my_filesize); // store the file in a variable
}
$prod_array = explode("~",$prod_doc); // create a array with the explode function
for($i=0; $i<count($prod_array); $i++){
$prod_items[$i] = explode(',', $prod_array[$i]); // create a malti-dimensional array
}
$query = "INSERT INTO my_table(feild1, feild two, feild three)
VALUES ('$prod_items[$i][0]','$prod_items[$i][1]','$prod_items[$i][2]')
";
$result = mysql_query($query);
if(!$result) die(mysql_error());
$result = mysql_affected_rows($result);
echo $result;
mysql_close($link); `
My problem is this: Array[0], Array[1], Array[3] is what is entered into the database instead of my data. Thanks in advance, cheers.
To access array variable element values used inside a double-quote string need braces delimiters:
"'{$prod_items[$i][0]}','{$prod_items[$i][1]}','{$prod_items[$i][2]}') ";
Another way to code this is by concatenation (in which case you don't need the extra delimiters):
"'" . $prod_items[$i][0] . "','" . $prod_items[$i][1] . "','" . $prod_items[$i][2] . "') ";
Don't forget, if the input data is unpredictable, you need to filter out characters that can break your sequel or compromise security principles. SEE How can I prevent SQL injection in PHP?
Also, junmats's comment is correct, you are only running the query outside the for loop which doesn't make sense.
You have to iterate over your $prod_items array as well, then concate the values
$insert = array();
for($i=0; $i<count($prod_array); $i++){
$prod_items[$i] = explode(',', $prod_array[$i]); // create a malti-dimensional array
$insert[] = '( ' .$prod_items[$i][0]. ', '.$prod_items[$i][1]. ', '. $prod_items[$i][3] .')';
}
$insert_string = implode(', ', $insert);
$query = "INSERT INTO my_table(feild1, feild two, feild three)
VALUES" . $insert_string;
And you should use foreach insted of for.
Seems like you've skipped some code.
After explode you'll have array of strings, not 2d array.
Also it's better to update the code a bit.
$query = "INSERT INTO my_table(feild1, feild_two, feild_three) VALUES ('".$prod_items[$i][0]."','".$prod_items[$i][1]."','".$prod_items[$i][2]."') ";
You should use the standard concatenation(.) technique for this.
PHP can only evaluate simple variables inside a string:
"$var" --> var is evaluated
"$var->var" --> is not evaluated
"$var[0]" --> is not evaluated
$query = "INSERT INTO my_table(feild1, feild two, feild three)
VALUES ('".$prod_items[$i][0]."','".$prod_items[$i][1]."','".$prod_items[$i][2]".')
";

Categories