How to send duble variable into one database(table) field? - php

In the first variable I store the name of a picture. The second one stores the path to this picture. The MySQL field should get both of them in order so I can access it from browser. How can I do this? I've already tried this:
$path = 'www.something.com/images/';
$sql = "INSERT INTO tb_user_info " . "(user_image)"."VALUES( '$path'.'$user_pic')";

Well first of all, you should be using prepared statements with mysqli or pdo. But to answer your question.
$path = 'www.something.com/images/' . $user_pic;
$sql = "INSERT INTO tb_user_info (user_image) VALUES( '$path')";

Related

php insert data from fetch array to other table on version 5.4

I have moved to IIS 8 in PHP 5.4. I am trying to collect data from a table and insert them to a different one, i know my code is correct, but seems to be not working, probably because of the php version, can anyone help me?
here's my code
$query = odbc_exec($conn, "SELECT * FROM member");
while($rows = odbc_fetch_array($query)) {
$querystring = "INSERT INTO oldusers (username, password, regdate) VALUES ('$rows['userid']', '$rows['passwd']', '$rows['registdate']')";
$query2 = odbc_exec($conn, $querystring);
odbc_free_result($query2);
//echo $rows['userid']." ".$rows['passwd']." ".$rows['registdate']."<br>";
}
thanks in advance.
instead trying to insert one by one record, better to insert like below:
INSERT INTO oldusers (username, password, regdate) SELECT userid,passwd,registdate FROM member
for more information :http://dev.mysql.com/doc/refman/5.5/en/insert-select.html
You're placing $rows['passwd'] inside of a double-quoted string. Instead you should do:
$str = "some sql $rows[passwd] rest of sql"; // notice the absence of single quotes
or:
$str = "some sql {$rows['passwd']} rest of sql";
or (I think this way is most readable):
$str = 'some sql' . $rows[passwd] . ' rest of sql';
If your column contains text you'll need to add surrounding single quotes where necessary.
Having said all that, you should instead use parameterized queries (if your database supports it) as it's safer (from SQL injection). If that's unavailable you will at the very least need to escape the data before concatenating it to the string.

Add suffix to an input data at the time of insert. Is this possible? (mySQL / php)

I need to add the letter "v" as a suffix to the end of the reg data every time I insert a new record in mySQL.
Here is my insert script. Is it possible to place the letter "v" to the reg data when the client submits this PHP action to insert?
<?
$order = "INSERT INTO reg_add (
connect_date,
reg,
first_name,
last_name)
VALUES
('$_POST[connect_date]',
'$_POST[reg]',
'$_POST[first_name]',
'$_POST[last_name]')";
$result = mysql_query($order);
if ($result) {
$reg = $_REQUEST['reg'] ;
$first_name = $_REQUEST['first_name'];
header("location: reg_add_success.php?reg=" . urlencode($reg) . "&first_name=" . urlencode($first_name));
}
else {
header("location: reg_add_fail.php");
}
?>
What you're doing is INCREDIBLY dangerous. You're basically offering a malicious user everything they need to perform a sql injection.
Collect your values, validate that they don't contain any malicious code, and then perform your insert (having added whatever suffixes you wanted)!!
Seriously... this is a disaster guaranteed to happen.
Check this out:
http://www.unixwiz.net/techtips/sql-injection.html
First, just append 'v' to the string.
Second,
You should NOT be using plain mysql library. You NEED TO be using mysqli (MySQL improved) library and be using prepared statements.
http://php.net/manual/en/mysqli.prepare.php
Otherwise your code is vulnerable to SQL Injection
$order = "INSERT INTO reg_add (
connect_date,
reg,
first_name,
last_name)
VALUES
('$_POST[connect_date]',
'{$_POST[reg]}v',
'$_POST[first_name]',
'$_POST[last_name]')";
Of cource you can. Just add $_POST[reg] .= 'v'; before $order = "....
$reg = stripslashes($_POST['reg']);
$reg = sprintf("%s%s",$reg,'v');
'".mysql_real_escape_string($reg)."',
Every VALUE has to has mysql_real_escape_string() function during making INSERT into MySQL.

PHP, trying to get $_POST['var'] into table as text

i'm having trouble with the code below. it's been simplified to show the problem. i use a loop because the input names are identical and need to create multiple new rows in a mysql table. the problem is i'm using $_POST['name'][$i] and the table won't accept because it doesn't see it as 'text?, ...i think.
like i said, code's been greatly simplified.
for($i=0;$i<count($_POST['url']); $i++) {
$sql = 'INSERT INTO urls (url) VALUES ('. $_POST['url'][$i].')';
if(!mysql_query($sql)) {
echo "error " . mysql_error();
}
}
i tried to rememdy with this -
$sql = 'INSERT INTO urls (url) VALUES ('. '"'. $_POST['url'][$i].'"'. ')';
if i do this it works, there is no error
$sql = 'INSERT INTO urls (url) VALUES (' " hello " ')';
this is probably a newbie type mistake, right? thanks for any help with this.
A cleaner way (and the errors are fixed):
$urls = (isset($_POST['url']) && is_array($_POST['url'])) ? $_POST['url'] : array();
foreach($urls as $url) {
if(!is_string($url)) {
continue;
}
$sql = "INSERT INTO urls (url) VALUES ('" . mysql_real_escape_string($url) . "')";
if(!mysql_query($sql)) {
echo "error " . mysql_error();
}
}
Making sure the $_POST['url'] is an array will keep from trying to treat a non array (or non-existent key) as an array. The is_string is to protect from a user trying to throw in a sub array to get PHP to throw a "using array as string" notice. The escape is to avoid SQL injection, and the single quotes added are so MySQL knows it's a string.
You simply need to add quotes around the POSTed value in your MySQL query like below. Also, if you don't escape the input, it's a massive SQL injection vulnerability:
$data = mysql_escape_string($_POST['url'][$i]);
$sql = 'INSERT INTO urls (url) VALUES ("'.$data.'")';
The query breaks MySQL because MySQL thinks your post value is supposed to be numeric without the quotes.
It would be helpful to see that actual error message returned by mysql_error() but I think your problem is that you're not providing the $_POST value to the sql query as thought it's text.
try replacing
$sql = 'INSERT INTO urls (url) VALUES ('. $_POST['url'][$i].')';
with
$sql = "INSERT INTO urls (url) VALUES ('". mysql_real_escape_string($_POST['url'][$i]) ."')";
You need to escape your $_POST variables before you insert them via an SQL statement, preferably using the mysql_real_escape_string() function to fortify your query against SQL injection attacks.
Answer provided by Corbin is good - however try not to fire insert queries in a loop.
You could create the sql query as one string and then fire the insert query once.
You could change your insert statement from
insert into table (field) values(1);
insert into table (field) values(1);
To:
insert into table (field) values(1), (2), (3), (4)...
This is a more optimal solution - however mysql has a max length to which it can take sql statements - therefore use your best judgement.
try this statement
$sql = "INSERT INTO urls (url) VALUES ('". mysql_real_escape_string($_POST['url'][$i])."')";

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)

uploadify and sql query

i am using uploadify script to upload files as my school project.
//die($_SESSION['ID'].'.....'.$_SESSION['level']);
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$filename = substr(md5(time()), 0, 8)."-".$_FILES['Filedata']['name'];
$targetFile = str_replace('//','/',$targetPath) . $filename;
$time = time();
$ID = $_SESSION['ID'];
$sql = mysql_query("INSERT INTO files VALUES(NULL, '$ID', '$targetFile', '$time')");
move_uploaded_file($tempFile,$targetFile);
echo "1";
}
On top $_SESSION['id'] is working, however when i entered inside $sql, it return as 0. Any idea why? i have rechecked everything.
Confused.
Thank you
It seems SESSION doesn't work well with uploadify, i solved it with scriptData uploadify.
Thank you for all answers.
Must be the type of your mysql column.
Be sure your are using varchar/text because '$ID' is a string : if your type is int (or similar) then you WILL have 0 inserted.
Couple things wrong here. You should first be explicitly naming your fields in the $sql:
$sql = 'insert into tablename (fileid,filename,d_uploaded) values ('.$ID.', \''.$targetFile.'\', '.$time.');';
Most ID fields won't be VARCHAR they will be INT. All VARCHAR is a text field and all INT are numeric. You don't escape out your INT fields but you need to escape your VARCHAR.
Also don't insert NULL fields to get an auto increment field. By doing the SQL the way I have above you get the benefit of being able to only code the SQL fields you are inserting and the rest of the fields in the table will insert default values.
Try using INSERT INTO files SET field=value, field=value, .. and remember to sanitize user input (like $_REQUEST) using mysql_real_escape_string() (and if you have magic quotes enabled to disable them if you decide to use mysql_real_escape_string().

Categories