Can't insert into my sql table - php

I get no errors with this code but i can't insert this row on my project table.
Is the problem in my date?
session_start();
$user = $_SESSION["username"];
if ( isset( $_POST["name"] )) {
$name = $_POST["name"];
}
if ( isset( $_POST["description"] ) ) {
$description = $_POST["description"];
}
if ( isset( $_POST["final"] ) ) {
$final = $_POST["final"];
}
if ( isset( $_POST["goal"] ) ) {
$goal = $_POST["goal"];
}
$sql = mysql_query("INSERT INTO project (name, description, final_date, funds, admin, goal) VALUES ('$name', '$description', '$final', '0', '$user', '$goal'");

You forgot to add a closing ) to your INSERT INTO statement.
The correct statement looks like this:
$sql = mysql_query(
"INSERT INTO project (name, description, final_date, funds, admin, goal)
VALUES ('$name', '$description', '$final', '0', '$user', '$goal');");
BTW, you should not use mysql_* anymore. Instead, the usage of mysqli_* or PDO is recommended.

Related

How do I insert a date value into a PostgreSQL table?

How to insert date in PostgreSQL? This seems to be wrong:
public function insert( $name, $author ) {
$this->query = "INSERT INTO people ( name, author, date )
VALUES ( '$name', '$author', to_timestamp('2/3/2016 12:05')";
return $result = pg_query( $this->connection, $this->query );
}
$database->insert( 'someName', 'SomeAuthor' );
'2016-03-02 12:05:00' is one way...
$this->query = "INSERT INTO people ( name, author, date )
VALUES ( '$name', '$author', '2016-03-02 12:05:00')";

PHP Can't get the ID of Last Record Inserted

I'm trying to get the ID of the last record inserted in my phpMyAdmin table, but I only get 0's so far.
I have tried almost everything (for example the solution on this answer: a link or what this page recommend : a link ) but I can't get it working.
My table has a column id that is the primary key and is marked as AUTO_INCREMENT.
I use a function query that make the connection to the database and then execute the queries:
function query($sql) {
$conn = mysqli_connect ( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
// Check connection
if (mysqli_connect_errno ()) {
echo 'connection failed: ' . mysqli_connect_error ();
}
// Check if the server is alive
if (mysqli_ping ( $conn )) {
// echo 'Connection is ok';
} else {
echo 'Error: ' . mysqli_error ( $dbc );
}
$sql = mysqli_query ( $conn, $sql );
$last_id = mysqli_insert_id( $conn );
$num_rows = mysqli_num_rows ( $sql );
$result = mysqli_fetch_assoc ( $sql );
return array (
"num_rows" => $num_rows,
"result" => $result,
"sql" => $sql,
"last_id" => $last_id
);
mysqli_close($conn);
}
Then I have another function from where I called the first one to execute the query:
function reg_shp_add($address_type, $company_name, $country, $state, $city, $zip, $street_name, $street_number, $tel){
if($address_type=="residential"){
$my_address_type = "r";
}else{
$my_address_type = "c";
}
$this->query ( "INSERT INTO `Addresses` (`company_name`, `street_address`, `address_two`, `zip_code`, `city_name`, `state_id`, `country_id`, `phone_number`, `res_comm_add`, `date_entered`) VALUES ('$company_name', '$street_name', '$street_number', '$zip', '$city', '$state', '$country', '$tel', '$my_address_type', CURRENT_TIMESTAMP)" );
$address_id = $sql ['user_id'];
$customer_id = $_COOKIE['userId'];
$this->query ( "INSERT INTO `Cust_address_type` (`cust_id`, ` mail_address_id`, `address_type`) VALUES ('$customer_id', '$address_id', 'Shipping')" );
return 'Address was saved.';
}
I first tried to retrieve the last id from my reg_shp_add function, but I guess it must be done from the first one.
Can anybody help me please?
I test your code and the function mysqli_insert_id work correctly with me ( ["last_id"]=> int(8) ). But the problem is in your second function, on the data retrieval ;
$this->query ( "INSERT INTO `Addresses` (`company_name`, `street_address`, `address_two`, `zip_code`, `city_name`, `state_id`, `country_id`, `phone_number`, `res_comm_add`, `date_entered`) VALUES ('$company_name', '$street_name', '$street_number', '$zip', '$city', '$state', '$country', '$tel', '$my_address_type', CURRENT_TIMESTAMP)" );
$address_id = $sql ['user_id'];
Here the $sql variable is undefined, you miss to store the return value into $sql, like that :
$sql = $this->query ( "INSERT INTO `Addresses` (`company_name`, `street_address`, `address_two`, `zip_code`, `city_name`, `state_id`, `country_id`, `phone_number`, `res_comm_add`, `date_entered`) VALUES ('$company_name', '$street_name', '$street_number', '$zip', '$city', '$state', '$country', '$tel', '$my_address_type', CURRENT_TIMESTAMP)" );
$address_id = $sql ['user_id'];

PDO transaction last inserted id in table1 to be used in table2

I have a form where I publish data to two different db tables. You can see my Transaction below.
$db->beginTransaction();
$sql = "INSERT INTO clients (name, contact_person, phone, email, url)
VALUES (:name, :contact_person, :phone, :email, :url)";
$stm = $db->prepare ( $sql );
$stm->bindParam ( ":name", $name );
$stm->bindParam ( ":contact_person", $contact_person );
$stm->bindParam ( ":phone", $phone );
$stm->bindParam ( ":email", $email );
$stm->bindParam ( ":url", $url );
$client = $stm->execute ();
//$last_id = $db->lastInsertId;
$sql = "INSERT INTO task (title, description, user_id, status_id, client_id)
VALUES (:title, :description, :user_id, :status_id ,:client_id)";
$stm = $db->prepare ( $sql );
$stm->bindParam ( ":title", $title );
$stm->bindParam ( ":description", $description );
$stm->bindParam ( ":user_id", $user_id );
$stm->bindParam ( ":status_id", $status_id );
//$stm->bindParam ( ":client_id", $last_id );
$task = $stm->execute ();
$db->commit();
However, in my table "task" I have another column "client_id" where I want to bind a value. And the value here, should be the same as the id value that has been auto-incrementet on my clients table.
I therefor need to somehow get the last insertet id from table one, and use that value in table two. I have outcommented my failed attempt, which didn't work, and returned NULL
Can anyone give me some pointers on how to manage this?
Use the function instead:
$last_id = $db->lastInsertId();
Put the execute statment of first tbl into
-----> if() condition
and get a last inserted id of table1 using
-----> $last_id = $this->conn->lastInsertId();
Replace your $sql query value
-----> :client_id replace with $last_id
here is the correct code (Remove the stars from code)
**if(**$client = $stm->execute ()**){**
**$last_id = $this->conn->lastInsertId();**
$sql = "INSERT INTO task (title, description, user_id, status_id, client_id)
VALUES (:title, :description, :user_id, :status_id ,**$last_id**)";
$stm = $db->prepare ( $sql );
$stm->bindParam ( ":title", $title );
$stm->bindParam ( ":description", $description );
$stm->bindParam ( ":user_id", $user_id );
$stm->bindParam ( ":status_id", $status_id );
$stm->bindParam ( ":client_id", $last_id );
$task = $stm->execute ();
$db->commit();
}

Inserting Date to Database

I'm trying to insert a date of birth into the database just one table but it's inserting 0000-00-00. I have a form that takes a date input or where <input type="date">. My insert command is:
if (($myname = $_GET['your_name']) && ($phone = $_GET['phone']) &&
($dob = date('Y-m-d', strtotime($_GET['dob'])))) {
$command = "INSERT INTO form_data (id, name, phone, dob)
VALUES ('', '".$db->real_escape_string($myname)."',
'".$db->real_escape_string($phone)."', '".$db->$dob."')";
My script works except the $dob. How do you handle an HTML5 input "date" input type into the database correctly? (I searched but didn't seem to work when I tried their suggestions here).
You assign date('Y-m-d', strtotime($_GET['dob']) to $dob, but later you try to reference it as $db->$dob. What you probably want it so to handle it just like the other variables and use $db->real_escape_string($dob):
$command = "INSERT INTO form_data (id, name, phone, dob)
VALUES ('', '".$db->real_escape_string($myname)."',
'".$db->real_escape_string($phone)."', '".$db->real_escape_string($dob)."')";
To make it more readable, I'd use sprintf though.
$command = sprintf("INSERT INTO form_data (id, name, phone, dob) VALUES ('', '%s', '%s', '%s')",
$db->real_escape_string($myname),
$db->real_escape_string($phone),
$db->real_escape_string($dob));
I suggest formatting your code so it's easier to read, and not doing assignments inside if blocks.
$myname = $_GET['your_name'];
$phone = $_GET['phone'];
$dob = strtotime( $_GET['dob'] );
if( !empty( $myname ) && !empty( $phone ) && $dob !== false ) {
$dob = date('Y-m-d', $dob );
$stmt = $dbConnection->prepare('INSERT INTO form_data ( id, name, phone, dob ) VALUES ( \'\', ?, ?, ? )');
$stmt->bind_param('s', $myname);
$stmt->bind_param('s', $phone);
$stmt->bind_param('s', $dob);
$stmt->execute();
$result = $stmt->get_result();
}
Note how I use mysqli instead of mysql_. It's safer.
By using $db->$dob in your VALUES set you're trying to access a member of $db called whatever value $dob is set to. You should be using $dob instead.

How to create sql insert query dynamically in mysql

I am creating an application where I am generating pins dynamically based on user's input and storing them into mySql database.
$sql = "INSERT INTO tblpin ('pinId', 'ownerId', 'usedby', 'status')
VALUES
for($i=0;$i<$npin;$i++)
{
('$pin[$i]','$ownerid', 'Free', '1');
}
;";
how can I do that?
$s = $pdo->prepare("INSERT INTO xy (a,b,c,d) VALUES (?,?,?,?)");
foreach ($pins as $i) {
$s->execute($i,$ownerID,"free",1);
}
Try this:
$sql = "INSERT INTO tblpin ('pinId', 'ownerId', 'usedby', 'status') VALUES ";
for($i=0; $i<sizeof($pin); $i++) {
if ($i>0)
$sql .= ", ";
$sql .= "('$pin[$i]', '$ownerid', 'Free', '1')";
}
Of course you need to escape the values of $pin in case they contain any characters which could mess with the SQL query.
Something like
$sql = sprintf( "INSERT INTO `tblpin` (`pinId`, `ownerId`, `usedby`, `status`) VALUES ('%s', '%s', '%s', '%s')",
generatePIN($pin),
mysql_real_escape_string($ownerId),
mysql_real_escape_string($usedBy),
mysql_real_escape_string( $status) );
or (edited for Conspicuous Compiler)
$pins = generatePINS($user); // ? however they're generated
foreach( $pins as $pin) {
$sql = sprintf( "INSERT INTO `tblpin` (`pinId`, `ownerId`, `usedby`, `status`) VALUES ('%s', '%s', '%s', '%s')",
$pin,
mysql_real_escape_string($ownerId),
mysql_real_escape_string($usedBy),
mysql_real_escape_string( $status) );
$result = mysql_query($sql);
}
where generatePIN is your function to make your pin based on whatever the heck you're basing it off of. or generatePINS returns an array of them

Categories