insertion problem in drupal 6 - php

Code:
$value["name"] = $form['name']['first'];
$contact = db_fetch_array(db_query("INSERT INTO test values('4', $value["name"])"));
error is shown here but what will be the correct code to submit $form data into a database?
Can anyone help me?
Thank you.

INSERT queries don't return a result, so there's nothing to fetch. Despite that your query is syntactically wrong: string values must be wrapped in quotes, numeric values must not.
db_query("INSERT INTO {test} VALUES (4, '%s')", $form['name']['first']);
As of Drupal 6 db_query("INSERT ...") is discouraged. drupal_write_record() should be used instead.
$record = array('id' => 4, 'firstname' => $form['name']['first']);
drupal_write_record('test', $record);
For more information please refer to the docs.

Related

PHP CodeIgniter Framework - Does Query Builder count as a prepare() and bind_param() and how to store form post data into Query Builder array?

I'm not finding much documentation-wise beyond some sources saying Query Builder statements are prepared, and others saying they are but not bound, then some saying they are bound etc. A solid answer would be much appreciated.
Furthermore, if I wanted to have my form data passed through into an array that I'm storing in my database, how should my following code be modified?
$user_first = $this->input->post('user_first');
$data['user_first'] = $user_first;
//this above code works fine if I want to store each part of the form
//in the array individually
$data = array(
'user_first' => 'My title'
//How can I get 'user_first' to => $user_first?
);
$this->pdo->insert('users', $data);
Thank you.
A few ways
//adding name by name to an array
$data = array('user_first' => $this->input->post('user_first'));
adding the entire post array
//as u have the same "name" in the form than the array u are sending to the db insert method
$data = $this->input->post();
//in short $this->input->post() is $_POST array, but cleaned
//or getting the values from $_POST
$data = array('user_first' => $_POST['user_first']);
Hope my answer helps u.
The answer depends to a large extent on what "prepared" means. "Binding" can be accomplished in a way very much like PDO. However, there are no methods that correspond to PDOStatement::bindColumn, PDOStatement::bindParam, or PDOStatement::bindValue.
The most direct equivalent to PDO::prepare() with "binding" would be as follows
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
The ? placeholders are replaced with the values in the array in the order they appear in the array. The input values will be escaped. The query() method does not support the PDO sytax of :name as a placeholder. (CI documentation on Query Binding.)
In general the various Query Builder methods combine to achieve the same overall effect as PDO::prepare() and PDOStatement::execute().
The functionality of PDOStatement methods to retrieve queried data (e.g. execute(), fetch(), etc.) are accomplished by calls to CI database methods for "Generating Query Results".
Assuming the three input from my example above have been posted by a here's how I would accomplish inserting them in a table
$data['id'] = $this->input->post('id');
$data['status'] = $this->input->post('status');
$data['author'] = $this->input->post('author');
$this->db-insert('some_table', $data);
If the element names are an exact match for the table column names and we know only those inputs will be posted the above could be simplified to
$this->db-insert('some_table', $this->input->post());

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.

Using PHP/PDO to set a NULL value

Using PHP/PDO I’m trying to set a MySQL (mysql-5.0.96) variable named “flt_status” whose default is set to ‘NULL’ and which is defined as INT(5), nullable, to NULL.
There are a number of threads here on StackOverFlow (11692773, 1391777) that cover this topic but none of them seems to work for me.
My (very abbreviated) code looks like this;
$vs = “:ip, flt_status, sunrise”;
$match = array(
‘:ip’=>”$ip”,
‘:flt_status’=>”null, PDO::PARAM_INT”,
’:sunrise’=>”$sunrise”
);
$vars = “ip, flt_status, sunrise”;
$sql = "INSERT INTO skeds ( $vars ) VALUES ( $vs )";
$query = $db_found->prepare( $sql );
$query->execute( $match );
I’ve tried a number of techniques outlined in the above discussions and others I’ve found using Google but every time the value of flt_status comes out as zero (0). I've tried using both PDO::PARAM_NULL and PDO::PARAM_INT.
I’ve included the IP and SUNRISE variables in this example so I can better understand any example the more experienced PHP/PDO programmers out there give me.
Can someone show me what I’m doing wrong?
Thanks in advance for any assistance you can offer.
You are doing several things wrong.
$vs = “:ip, flt_status, sunrise”;
First, you're apparently using smart quotes instead of straight quotes. Code needs straight quotes.
Next, you put a : prefix before ip but you missed that prefix before the other two named parameters. You need a : before each one.
$match = array(
‘:ip’=>”$ip”,
‘:flt_status’=>”null, PDO::PARAM_INT”,
’:sunrise’=>”$sunrise”
);
Next, you put null inside a quoted string. That makes it a string literal containing the word 'null', not a true null. These two concepts are different, like the difference between a chicken and a piece of paper with the word "chicken" written on it.
Also, you don't need to put quotes around the variables.
Also, for what it's worth, the : prefix on the array keys of your array are optional. In early versions of PDO, they were mandatory, but now they're not. It does no harm to keep the colon prefix, I just wanted to let you know because it could make it easier in the future to prepare arrays of parameters from another associative array, like $_POST.
$vars = “ip, flt_status, sunrise”;
This is fine except for the continued use of smart quotes.
$sql = "INSERT INTO skeds ( $vars ) VALUES ( $vs )";
Here's where you will get into trouble with your $vs because it contains only one parameter placeholder, followed by two plain column names. Passing column names in the VALUES clause is not illegal in SQL, but it makes no sense to do it.
$query = $db_found->prepare( $sql );
$query->execute( $match );
Okay, except that you are not checking for errors. Unless you have enabled PDO's attribute for throwing exceptions, you need to check the return status of prepare() and execute() because they return false if there's any error. This continues to be one of the most common mistakes among PHP developers!
Here's how I would write this code.
As you connect to PDO, enable exceptions. See http://php.net/manual/en/pdo.error-handling.php
$db_found = new PDO(...);
$db_found->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Then the code for this routine:
$placeholders = ":ip, :flt_status, :sunrise";
$values = array(
'ip' => $ip,
'flt_status' => null,
'sunrise' => $sunrise
);
$columns = "ip, flt_status, sunrise";
$sql = "INSERT INTO skeds ($columns) VALUES ($placeholders)";
$stmt = $db_found->prepare($sql);
$stmt->execute($values);
You have few mistakes in your code, try to adjust it like this:
$sql = "INSERT INTO skeds ( ip, flt_status, sunrise ) VALUES ( :ip, :flt_status, :sunrise )";
$query = $db_found->prepare( $sql );
$query->execute( array(':ip'=> $ip,
':flt_status'=>null,
':sunrise'=>$sunrise
));
When you say
$match = array(
‘:ip’=>”$ip”,
‘:flt_status’=>”null, PDO::PARAM_INT”,
’:sunrise’=>”$sunrise”
);
it's going to use that actual string "null, PDO::PARAM_INT". If you want a NULL, bind the placeholder to the PHP value null.
You have to understand the difference between strings and PHP code.
"null, PDO::PARAM_INT" IS a string. You cannot store PHP code in a string.
"null" AGAIN is not a NULL value either but a string contains word " null
If you want ot bind a null, then just bind PHP NULL value. Yes, as simple as that.

Strange issue in this query. It is not inserting a particular value

I have an insert process. My development is under Drupal6. So i used the following method to insert into database table.
$sid = $user->sid;
$data = array(
'nid' => $parent_nid,
'vid' => $parent_vid,
'uid' => $user_id,
'time_start' => time(),
'session_id' => $sid
);
drupal_write_record('quiz_node_results', $data);
Here the problem is, it is not inserting the value $sid. It inserts the default value 0 always in that field. But other values are inserted correctly. But it has value. I checked with by putting print_r($data).
In database table, session_id field's datatype is varchar.
For quick fix, i wrote actual insert query and inserted into it. That query is below.
$sql = "INSERT INTO {quiz_node_results}(nid, vid, uid, time_start, session_id) VALUES(".$parent_nid.",".$parent_vid.",".$user_id.",".time().", '".$sid."')";
db_query($sql);
It is working fine and inserts the value correctly. But i don't want to insert in this way because it is vulnerable.
I want to know why the above one is not working. Can anyone suggest where i went wrong?
I'm pretty sure changing line 1 from this:
$sid = $user->sid;
to this:
$sid = isset($user->sid) ? $user->sid : session_id();
should do the trick...

passing array to function

Hello everyone please help me out regarding this this piece of code
$user = new User();
$user->connect();
$pno=$_POST['pno'];
$name=$_POST['name'];
$age=$_POST['age'];
$result = array('name'=>$name,'age'=>$age,'pno'=>$pno);
$error=$user->edit($result);
$user->disconnect();
I want to coustomize these line of code
$pno=$_POST['pno'];
$name=$_POST['name'];
$age=$_POST['age'];
$result = array('name'=>$name,'age'=>$age,'pno'=>$pno);
I mean like this
$result = array('$_POST['name']'=>$name,'$_POST['age']'=>$age,'$_POST['pno']'=>$pno);
but i am unable to put '' properly please help me out regarding this and a small simple hints about qoutes. Thanks
$result = array($_POST['name']=>$name,$_POST['age']=>$age,$_POST['pno']=>$pno);
The reason why your code was failing was because you are trying to interpolate $_POST['name'] in a string with single quotes, which will fail because $_POST['name'] also contains single quotes(this will raise a Parse error).
You're breaking up the string with the nested quotes. Use "..." in stead, like this:
$result = array('$_POST["name"]'=>$name, '$_POST["age"]'=>$age,'$_POST["pno"]'=>$pno);
That said, personally I'd go for more descriptive and less cluttered field names, like "name", "age", etc...
$result = array(
'name' => $_POST['name'],
'age' => $_POST['age'],
'pno' => $_POST['pno']
);
$result = array($_POST['name']=>$name, $_POST['age']=>$age, $_POST['pno']=>$pno);
That should be work however your array key index will be mixed with number and string, plus your code doesn't work because you use " ' " witch will interpret $_POST['age'] as a string if it work, double quote can understand variable inside it.
If you really want the whole variable name as the key for each of the results variable you could but why?
$results['$_POST["name"]'] = $name;
$results['$_POST["age"]'] = $age;
$results['$_POST["pno"]'] = $pno;

Categories