I have ajax which takes data (id, companyName, owed, oldRem) from a table in categorylist.php which is used in remit.php. Below is my ajax code categorylist.php which gets data from table row and it works well.
<script>
function payCompany(id, companyName, owed, oldRemit){
swal("Enter Amount:", {
title: companyName,
buttons: true,
closeModal: true,
content: "input",
})
.then((amount) => {
if (amount === "") {
swal("Oops!! You need to enter value.");
return false
}else{
$.ajax({
type: 'POST',
url: 'remit.php',
data:{
rid: id,
pay: amount,
company_Name: companyName,
old_Remit: oldRemit,
debt_owed: owed,
<?php
echo ' currentDate : "'.$savedate.'",'
?>
},
success: function(data){
swal(`Paid: ${amount} to ${companyName}`);
},
error: function(data){
swal(`Error remitting: ${amount} to ${companyName}`);
}
});
}
});
}
</script>
my code in remit.php. I couldn't confirm if the code is passed to remit.php from ajax. there was no error displayed when it was run.
<?php
#remit.php
/*
If you are using sessions you need to start a session!
*/
error_reporting( E_ALL );
session_start();
if( empty( $_SESSION['useremail'] ) OR empty( $_SESSION['role'] ) OR $_SESSION['role']=="Admin" ){
exit( header('Location: index.php') );
}
/*
Check that all fields that are required in the SQL have been submitted
*/
if( isset(
$_POST['rid'],
$_POST['pay'],
$_POST['currentDate'],
$_POST['compnyName'],
$_POST['old_remit'],
$_POST['debt_owed']
) ){
try{
include_once 'connectdb.php';
/*
When inserting, updating multiple tables there is some sense in using a transaction
so that if one part fails the db is not littered with orphan records
*/
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$pdo->beginTransaction();
$remitID = $_POST['rid'];
$new_remit = (double)$_POST['pay'];
$company = $_POST['compny_Name'];
$old_rem = (double)$_POST['old_remit'];
$total_debt = (double)$_POST['debt_owed'];
$current_date = $_POST['currentDate'];
$paid = $new_remit + $old_rem;
$currentDebt = $total_debt - $paid;
/*
The SQL command should use placeholders rather than embedded variables - the names are arbitrary
*/
$sql='INSERT INTO `tbl_category_remits` ( `payment_date`, `category`, `remitted` )
VALUES
( :pay_date, :comp, :remit )';
$stmt=$pdo->prepare( $sql );
$args=array(
':pay_date' => $current_date,
':comp' => $company,
':remit' => $new_remit
);
if( !$stmt->execute( $args ) )echo 'stmt#1 failed';
$sql='UPDATE `tbl_category` SET `remitted` =:payment , `debt` =:current_debt WHERE `catid`=:rid';
$stmt=$pdo->prepare( $sql );
$args=array(
':current_debt' => $currentDebt,
':payment' => $paid,
':rid' => $remitID
);
if( !$stmt->execute( $args ) )echo 'stmt#2 failed';
/*
If it all went well, commit these statements to the db
*/
if( !$pdo->commit() )echo 'commit failed';
}catch( PDOException $e ){
/*
Any problems, rollback the transaction and report issues -
not necessarily with the full `getMessage()` ~ perhaps just
'Error!' etc
*/
$pdo->rollBack();
echo $e->getMessage();
}
}else{
echo $e->getMessage();
}
?>
On the above code, I have an insert statement as well as update statements, both to different tables as shown below:
Please, what's wrong with my code? It doesn't seem to update and insert into the database. Please, I need help with this code!!
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm creating simple web application using php. And there is basic constant settings in (config.php) like:
define('SITE_NAME', 'Site A');
define('SITE_URL', 'https://example.com');
define('SITE_EMAIL', 'test#example.com');
define('SENDGRID_API', 'G.6786jka9769fhgg45479989hjvh');
And calling this file almost every page. Is it possible to store this value in mysql and it's editable via web interface for admin? If yes, how to do it? So that i don't need to connect to db for everytime using this constant. If i'm not mistaken, some settings from wordpress is using something like this.
For your solution create a table like:
DROP TABLE IF EXISTS `settings`;
CREATE TABLE IF NOT EXISTS `settings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`site_option` varchar(200) NOT NULL,
`site_value` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
COMMIT;
Needs 4 files: index.php, db.php, create.php, update.php
db.php
function connect()
{
$dsn = 'mysql:host=localhost;port=3306;dbname=update;';
try{
return new PDO($dsn, 'root', '');
}catch( \Exception $e ){
return $e->getMessage();
}
}
index.php
<?php
session_start();
?>
<htmL>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<title>Test UPDATING records in PHP</title>
</head>
<div>
<?php
if(isset($_SESSION['success'])){
echo $_SESSION['success'];
}elseif(isset($_SESSION['error'])){
echo $_SESSION['error'];
}
//clearing all session values
session_unset();
?>
<h2>Create New Site Option / Setting</h2>
<form action="create.php" method="POST">
Site Option: <input type='text' name='site_option' size='12' value=''>
Site Value: <input type='text' name='site_value' size='12' value=''>
<input type="submit" value="Submit">
</form>
</div>
<?php
require_once('db.php');
$pdo = connect();
if( $pdo instanceof \PDO ){
$sql = "SELECT * FROM settings";
$dbh = $pdo->prepare($sql);
var_dump($dbh);
$dbh->execute();
foreach($dbh as $row){
echo "<div style='padding-bottom:1em;' class='datarow'>";
echo "<input type='text' name='site_option' size='12' value='{$row['site_option']}'>";
echo "<input type='text' name='site_value' size='3' value='{$row['site_value']}'>";
echo "<input type='hidden' name='id' size='3' value='{$row['id']}'>";
echo "<button onClick='updateValues(this);'>Update Option</button>";
echo "</div>";
//define the constant
if (!defined($row['site_option'])) {
define( strtoupper($row['site_option']),$row['site_value']);
}
}
// To see all constants , uncomment if you need to see them for testing
// print_r(get_defined_constants(true));
}else{
//echo $pdo->getMessage();
}
?>
<script type="text/javascript">
function updateValues(obj){
let datarow = $(obj).closest('.datarow');
//("input[name='quantity']").val()
console.log($('input[name="author"]', datarow).val());
$.post( "update.php", { site_option: $('input[name="site_option"]', datarow).val(),
site_value: $('input[name="site_value"]', datarow).val(),
id: $('input[name="id"]', datarow).val()
//id: $(obj).data('parentid')
}
).done(function( data ) {
if( ! $.isEmptyObject( data.error ) ) {
alert( 'error' + data.error);
}else{
//success
alert( 'Success: ' + data.success );
location.reload();
}
});
}
</script>
</htmL>
create.php
session_start();
require_once('db.php');
if(isset($_POST['site_option']) && isset($_POST['site_value'])){
//Todo: do some sort of validation / sanity checking (dont trust user input)
$site_option = $_POST['site_option'];
$site_value = $_POST['site_value'];
$sql = "INSERT INTO settings ( id, site_option, site_value ) VALUES ( NULL, :site_option, :site_value )";
$pdo = connect();
$dbh = $pdo->prepare($sql);
try{
$dbh->execute( [
':site_option' => $site_option,
':site_value' => $site_value
] );
$_SESSION['success'] = 'Successful creation of new record';
header("Location: index.php");
}catch( \Exception $e ){
$_SESSION['error'] = 'Error creating new entry';
//echo json_encode( [ 'error' => $e->getMessage() ] );
}
}
update.php
require_once('db.php');
header('Content-Type: application/json');
if(isset($_POST['id'])){
//Todo: do some sort of validation / sanity checking (dont trust user input)
$sql = "UPDATE settings SET site_option=:site_option, site_value=:site_value WHERE id=:id";
$pdo = connect();
$dbh = $pdo->prepare($sql);
try{
$dbh->execute( [
':site_option' => $_POST['site_option'],
':site_value' => $_POST['site_value'],
':id' => $_POST['id']
] );
echo json_encode( [ 'success' => 'Record updated.' . $_POST['site_option'] ] );
}catch( \Exception $e ){
echo json_encode( ['error' => 'Error updating the record' ]);
//echo json_encode( [ 'error' => $e->getMessage() ] );
}
}
I'm trying to insert from data into my database but it won't work for some reason. I keep getting the following error when submitting the form: Error: INSERT INTO voorwerpenlijst (beschrijving, waar, wanneer, ophalen) VALUES ('value', 'value', 'value', 'value')
Access denied for user 'id11961846_profielwerkstuk'#'%' to database 'voorwerpenlijst'. When i leave out the $sql part i am able to connect to the database just fine so the login credentials are correct. I ran the same PHP using XAMPP and phpmyadmin from my own PC and it worked just fine. This confirmed for me that my code should be fine, but it's still not working with 000webhost. I'm using the database I got through 000webhosting which doesn't allow me to change any of the privileges in phpmyadmin. Any sql statement i try to use gets blocked.
thanks in advance
<html lang="nl">
<meta charset = "utf-8">
<head>
<link rel="stylesheet" href="profielwerkstukSTYLE.css">
<ul>
<li>Home</li>
<li><a class="active" href="upload.php">upload voorwerp</a></li>
<li>voorwerp lijst</li>
</ul>
</head>
<body>
<h3>Upload het door u gevonden voorwerp<h3><br>
<div>
<form action="upload.php" method="post" enctype="multipart/form-data">
Beschrijving:<br> <input type="text" name="beschrijving" placeholder="bijv. jas, airpods, sleutels etc."><br>
Waar:<br> <input type="text" name="waar" placeholder="bijv. lokaal 117"><br>
Wanneer:<br> <input type="text" name="wanneer" placeholder="bijv. 5e uur"><br>
ophalen waar:<br> <input type="text" name="ophalen" placeholder="bijv. bij de balie"><br>
<input type="submit" value="verzend" name="knop">
</form>
<div>
<?php
if(
isset($_POST["beschrijving"])&& $_POST["beschrijving"]!="" &&
isset($_POST["waar"]) && $_POST["waar"]!="" &&
isset($_POST["wanneer"]) && $_POST["wanneer"]!="" &&
isset($_POST["ophalen"]) && $_POST["ophalen"]!="")
{
$host="localhost";
$username="id11961846_profielwerkstuk";
$password="12345";
$dbname="voorwerpenlijst";
$conn= mysqli_connect("$host", "$username", "$password", "$dbname");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$beschrijving=$_POST["beschrijving"];
$waar=$_POST["waar"];
$wanneer=$_POST["wanneer"];
$ophalen=$_POST["ophalen"];
$sql = "INSERT INTO voorwerpenlijst (beschrijving, waar, wanneer, ophalen)
VALUES ('$beschrijving', '$waar', '$wanneer', '$ophalen')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
else
{
if(isset($_POST["knop"]))
{
print("Vul A.U.B alles in");
}
}
?>
</body>
</html>
Your code is vulnerable to SQL injection - a better way to perform this insert would be to use a prepared statement ~ it might help solve your issue too
<?php
$errors=[];
$args=array(
'beschrijving' => FILTER_SANTITIZE_STRING,
'waar' => FILTER_SANTITIZE_STRING,
'wanneer' => FILTER_SANTITIZE_STRING,
'ophalen' => FILTER_SANTITIZE_STRING,
'knop' => FILTER_SANTITIZE_STRING
);
foreach( array_keys( $args ) as $field ){
if( !isset( $_POST[ $field ] ) ) $errors[]=sprintf( 'The field "%s" is not set', $field );
}
foreach( $_POST as $field => $value ){
if( !in_array( $field, array_keys( $args ) ) )$errors[]=sprintf( 'Unknown field "%s"', $field );
}
if( empty( $errors ) ){
/* filter incoming POST array */
$_POST=filter_input_array( INPUT_POST, $args );
/* create variables */
extract( $_POST );
$host="localhost";
$username="id11961846_profielwerkstuk";
$password="12345";
$dbname="voorwerpenlijst";
$conn=new mysqli( $host, $username, $password, $dbname );
$sql='insert into `voorwerpenlijst` ( `beschrijving`, `waar`, `wanneer`, `ophalen` ) values (?,?,?,?)';
$stmt=$conn->prepare( $sql );
if( !$stmt )$errors[]='failed to prepare sql';
$stmt->bind_param( 'ssss', $beschrijving, $waar, $wanneer, $ophalen );
$res=$stmt->execute();
$stmt->close();
echo $res ? 'New record created successfully' : 'error';
} else {
/* display errors? */
}
?>
I'm new to coding.
I have to make a website, where images are retrieved from MySQL database using PHP functions, but I can't store images in the DB, only their names, and I can't manually put in the id as in getImage(1) etc.
So I have these two functions:
function getImage($imgid) {
$sql_command = "SELECT * FROM images WHERE id=$imgid;";
$result = mysqli_query(getConnection(), $sql_command);
if($result) {
$result = mysqli_fetch_assoc($result);
return $result;
} else {
echo "Error <br /> " . mysqli_error(getConnection());
return NULL;
}
}
function getImages() {
$sql_command = "SELECT * FROM images;";
$result = mysqli_query(getConnection(), $sql_command);
if($result) {
return $result;
} else {
echo "Error.";
return NULL;
}
}
I then included the file in my index.php but, honestly, I lack understanding on how to actually apply these functions and specify the name of the image, since it's a variable.
I don't expect someone to solve this problem for me, just to explain the logic or maybe share a link to a useful resource that would explain a situation like this.
Typically the image will be in a directory. And the name of the image will be saved in the database. You can then make a query to receive all image names and display them using a loop
$sql = "SELECT * FROM images";
$imageresult1 = mysql_query($sql);
while($rows=mysql_fetch_assoc($imageresult1))
{
$image = $rows['image'];
echo "<img src=/path/to/'$image' >";
echo "<br>";
}
I'm not sure if I understand exactly what you want to do, but in the database you have to save the path where it will be saved imagine on the server, then you can list them.
<?php
function getImages() {
$sql_command = "SELECT * FROM images;";
$result = mysqli_query(getConnection(), $sql_command);
if($result) {
$imgs = [];
while($rows=mysql_fetch_assoc($result)) {
$imgs[] = $rows;
}
return $imgs;
} else {
echo "Error.";
return NULL;
}
}
// list imgs
$imgs = getImages();
foreach($imgs as $img) {
echo "<img src'{$img['path']}' />";
}
Hopefully the following might give an idea how to use the functions you already have and, with a little work, implement the use of getImage($id) by using ajax. The code below will display the images found by querying the db ( assuming the db table has a structure similar to this )
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(512) | YES | | NULL | |
+-------------+------------------+------+-----+---------+----------------+
And also assuming that the column name stores the fullpath to the image rather than just the image name itself.
<?php
function getConnection(){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
return $db;
}
function getImages(){
/*
query the database to return the ID and name of ALL images
*/
try{
/* two named fields - these will be returned later */
$sql='select `id`,`name` from `images`';
/* Get the db conn object */
$db=getConnection();
/* throw exception if we are unable to bind to db */
if( !$db or !is_object( $db ) ) throw new Exception('Failed to bind to database');
/* query the db */
$res=$db->query( $sql );
/* throw an exception if the query failed */
if( !$res ) throw new Exception('sql query failed');
/* prepare results and iterate through recordset */
$results=array();
while( $rs=$res->fetch_object() ) $results[ $rs->id ]=$rs->name;
/* return the array of results */
return $results;
}catch( Exception $e ){
echo $e->getMessage();
return false;
}
}
function getImage( $id=false ){
/*
Query the database to return single image based upon ID
*/
try{
/* If the id is not specified or empty throw exception */
if( !$id )throw new Exception('Image ID was not specified');
/* sql statement to execute */
$sql='select `name` from `images` where `id`=?';
/* get db conn object */
$db=getConnection();
/* throw exception if we are unable to bind to db */
if( !$db or !is_resource( $db ) ) throw new Exception('Failed to bind to database');
/* Create a "Prepared Statement" object - avoid SQL injection !! */
$stmt=$db->prepare( $sql );
/* If the statement failed, throw exception */
if( !$stmt )throw new Exception('Failed to prepare sql query');
/* Bind the supplied ID to the sql statement */
$stmt->bind_param( 'i', $id );
/* Execute the query */
$res=$stmt->execute();
if( $res ){
/* Prepare results */
$stmt->store_result();
$stmt->bind_result( $name );
$stmt->fetch();
/* return the name of the image */
return $name;
} else {
throw new Exception('sql query failed');
}
}catch( Exception $e ){
echo $e->getMessage();
return false;
}
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Images</title>
<style>
#images{
width:90%;
float:none;
display:block;
margin:1rem auto;
}
#images > img {
float:none;
margin:1rem;
padding:1rem;
border:1px dotted gray;
}
</style>
<script>
document.addEventListener( 'DOMContentLoaded', function(){
var col=Array.prototype.slice.call( document.getElementById('images').querySelectorAll('img') );
col.forEach(function(img){
img.onclick=function(e){
alert('You could send an ajax request, using the ID:' + this.dataset.imgid + ' and then use PHP at the server side to process the ajax request and return the specific image using "getImage(id)"')
}
});
}, false );
</script>
</head>
<body>
<div id='images'>
<?php
$images = getImages();
if( !empty( $images ) ){
foreach( $images as $id => $name ){
echo "<img data-imgid='$id' src='$name' title='This image is called $name and has db ID $id' />";
}
}
?>
</div>
</body>
</html>
This question already has answers here:
How do I display a MySQL error in PHP for a long query that depends on the user input? [duplicate]
(6 answers)
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 5 years ago.
I'm trying to insert values in table it is saying error please tell me where i'm wrong here is my code
its said please try again
<?php
include_once('dbconnect.php');
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$phone = $_POST['phone'];
$cash = $_POST['cash'];
if(mysql_query("INSERT INTO tbl2 VALUES('',$name','$phone','$cash','date('l jS \of F Y h:i:s A'))"))
echo "Successful Insertion!";
else
echo "Please try again";
}
$res = mysql_query("SELECT * FROM tbl2");
?>
<form action="" method="POST">
<input type="text" name="name"/><br />
<input type="text" name="phone"/><br />
<input type="text" name="cash"/><br />
<input type="submit" name="submit" value=" Enter "/>
</form>
<h1>List of companies ..</h1>
<?php
while( $row = mysql_fetch_array($res) )
echo "$row[id].$row[Name]
<a href='edit.php?edit=$row[id]'>edit</a><br />";
?>
will you guide me i thought the problem is in date date
Two things I can think of top my head;
mysql_ has been deprecated, thus the else kicks in.
Your syntax maybe wrong for mysql_query?
Nonetheless, start over and start over with code that is functional and up-to-date...
Given that your connection is working properly update it to a new mysqli syntax, it's very simple and much more elegant:
$connect = new mysqli( 'localhost', 'USERNAME', 'PASSWORD', 'DATABASE' );
// check for an error
if ($this->_connection->connect_error)
{
trigger_error("Connection Error: " . $this->_connection->connect_error(), E_USER_ERROR);
}
Now that you are connected walk-through a new process for your code.
Start by checking like you currently are for a submit $_POST so that you can start running the script:
if ( isset( $_POST['submit'] ) )
{
// Encode the URL when creating the variables
$name = htmlentities( $_POST['name'] );
$phone = htmlentities( $_POST['phone'] );
$cash = htmlentities( $_POST['cash'] );
$date = date( 'l jS \of F Y h:i:s A' );
// create sql
// DO NOT INSERT VALUES STRAIGHT INTO YOUR QUERY
$sql = "INSERT INTO tbl2 ( name, phone, cash, date ) VALUES ( ?, ?, ?, ? )";
Note: before continuing, let me explain that you should never insert content into your query because that would throw raw user input in the mist of your code. Now, most users will never try anything fishy. But anyone could easily throw a few SQL commands inside of your inputs and DELETE, SELECT, and UPDATE your database content and cause numerous problems.
Here is some reference: https://en.wikipedia.org/wiki/SQL_injection
To work around that problem, use prepared statements. You can read all about it on PHP manual; and also see some real-life examples.
// prepare query
// USE PREPARED STATEMENTS
if ($stmt = $connect->prepare( $sql ))
{
// bind the params
$stmt->bind_param('ssss', $name, $phone, $cash, $date);
// execute the query
$stmt->execute();
// check for errors
if ($stmt->errno)
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: ' . $stmt->error
);
}
// make sure at least 1 or more rows were affected
if ($stmt->affected_rows > 0)
{
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' rows were inserted.' // value should be 1
);
}
else
{
// if not, send warning to user
$message = array(
'is_error' => 'warning',
'message' => 'Warning: ' . $stmt->affected_rows . ' rows were updated.'
);
}
// close your connection
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'QUERY: error. Try again.'
);
exit;
}
}
else
{
$message = array(
'is_error' => 'warning',
'message' => 'There was no submission attempt. Try again.'
);
exit;
}
Notice in the code is broken down into parts where you can catch multiple errors, and it's important for debugging; it will allow you to know exactly where the code went wrong, and localize your problem to a single section of it.
I am making a plugin in wordpress. And I am trying to get the post id when I click the publish button on the add new post. And now, I get an internal error(500) when I use the get post function.
I am using_POST['post'] now, but how can I use the wordpress function to get the post id?
Here is my code:
//require the php
require_once( FACEBOOK_API_PLUGIN_DIR . 'js/databaseConnection.php' );
Code on databaseConnection.php:
function get_post()
{
global $wp_query;
$thePostID = $wp_query->post->ID;
return $thePostID;
}
function try_insert($post_id)
{
$test02 = 333243;
$test03 = 222;
$link = #mysqli_connect(
'localhost',
'root',
'',
'wordpress'
) or die("connection failed");
$sql = "INSERT INTO post_data02 (post_id, condition_code) VALUES ('$post_id','$test03')";
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link -> error;
}
$link->close();
}
add_action( 'publish_post', 'try_insert', get_post());
Also, when I disable the get_post() function I error will be gone. What am I doing wrong?
thanks,
You don't need get_post at all and you are using the publish_post hook and add_action function incorrectly.
Additionally, have a look at the WPDB class. If your table is in the same database and schema as your WordPress tables you don't need to use mysqli_connect - WordPress has already connected to the database for you!
Note also that you should NEVER pass values into a string to be used as part of an SQL statement! This is a MASSIVE security risk! ALWAYS use prepared statements and parameters (WPDB provides this as well).
Try this:
function try_insert($post_id, $post)
{
// Pull in the global WPDB variable WordPress creates
global $wpdb;
$test02 = 333243;
$test03 = 222;
/*
* Insert record into the table "post_data02" with the values:
* "post_id" => The ID in $post_id passed by WordPress,
* "condition_code" => The number in $test03 (currently 222)
*/
$insert = $wpdb->insert( 'post_data02',
[ 'post_id' => $post_id, 'condition_code' => $test03 ],
[ '%d', '%d' ]
);
if( $insert !== false ) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link -> error;
}
}
add_action( 'publish_post', 'try_insert', 10, 2);
Please re-read the links I provided above as they provide excellent examples and show you how to use the functions, methods, hooks, etc.