Insert current page, id, date into mySQL table - php

In my Joomla 2.5.14 I'm trying to insert the current page_id, user_id and date into a mySQL table (called xmb9d_hist).
This is the code I'm using:
<?php
/* Define $jinput */
$jinput = JFactory::getApplication()->input;
/* Get the current page id */
$page= $jinput->get('id');
/* Get the current user id */
$user =JFactory::getUser();
$usr_id = $user->get('id');
/* Get the current date */
$date =JFactory::getDate();
/* Open a connection */
$link=mysqli_connect('localhost','peter','abc123');
if(!$link){
echo "Não há ligação!";
exit();
};
/* Insert current user id, page id and date in to table xmb9d_hist */
mysqli_query($link, "INSERT INTO `portalge_formacao`.`xmb9d_hist` (`user_id`, `page_id`, `date`) VALUES ($usr_id, $page, $date)");
/* Close connection */
mysqli_close($link);
?>
The first part of the code is working ok (retrieving the values for the 3 variables. However, the data isn't being inserted in the database and no error is produced.
In MySQL table, user_id and page_id are defined as INT(11) and date as date.
Thanks in advance for your help.

You need to stick to Joomla coding standards when using Joomla unless they have not provided a class for whatever you need. Have a read of the documentation before trying something just incase there is information about it.
Try using the following:
<?php
$db = JFactory::getDbo();
$date = JFactory::getDate();
$user = JFactory::getUser();
$jinput = JFactory::getApplication()->input;
$page= $jinput->get('id');
$usr_id = $user->get('id');
$query = $db->getQuery(true);
$columns = array('user_id', 'page_id', 'date');
$values = array($usr_id, $page, $date);
$query
->insert($db->quoteName('#__hist'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
$db->setQuery($query);
?>
Hope this helps

I see a few issues with your insert query. First off, I believe that JFactory::getDate() returns an object, so to get something you can insert into the database you want to do a toFormat() on it. Try changing your line from:
$date =JFactory::getDate();
to this:
$date =JFactory::getDate()->toFormat();
And since the date isn't an integer, you need to escape the string in your insert, so update that line to this:
mysqli_query($link, "INSERT INTO `portalge_formacao`.`xmb9d_hist` (`user_id`, `page_id`, `date`) VALUES ($usr_id, $page, '$date')");

You should use the method toSql() , it's for SQL e.g.
$date = JFactory::getDate()->toSql();
hope this helps

Related

inserting data to database doesnt work(PHP)

im trying to insert data into a db and I have no clue why its not working.
if(isset($_POST['reply_msg']))
{
$date = date("Y-m-d H:i:s");
$sql = mysql_query("INSERT into pm
(sent_to, sent_by, date, title, content, status)
VALUES('%s','%s','%s','%s','%s','%s')"
, $MSGInfo['sent_by']
, $MSGInfo['sent_to']
, $date
, mysql_real_escape_string($_POST['reply_title'])
, mysql_real_escape_string($_POST['reply_conent'])
, 'Unread');
if (!$sql){
die('Sending failed ');
}
else echo 'Sent!';
}
table screenshot: http://prntscr.com/a2r47v
You should build your query PHP style, not C style. Even so, I would not recommend mysql for this, mysqli is better. Also, take a look at PDO for a higher level of security.
// setup query
$q = "INSERT INTO `pm` ('sent_to', 'sent_by', 'date', 'title', 'content', 'status')) VALUES(
$MSGInfo['sent_to'],$MSGInfo['sent_by'],$date,
mysql_real_escape_string($_POST['reply_title']), mysql_real_escape_string($_POST['reply_conent']),Unread)";
//Run Query
$result = mysql_query($q) or die(mysql_error());
Your query is not quite well built, you need to work a little more at it.

Stuck at this error: Incorrect integer value: '' for column '____' at row 1

When I submit the form and use this script to insert the data in the db i get the error mentioned above...any ideas?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proCode = $_POST["code"];
$proDescr = $_POST["description"];
$proManu = $_POST["manufacturer"];
$proCPU = $_POST["cost_per_unit"];
$proWPU = $_POST["weight_per_unit"];
$proBarCode = $_POST["bar_code"];
$proIngredients = $_POST["ingredients_list"];
$proAllergens = $_POST["allergens_contains"];
$proMayAllergens = $_POST["allergens_may_contain"];
//Insert users data in database
$sql = "INSERT INTO prodb.simplex_list
code, description, manufacturer,
cost_per_unit, weight_per_unit, bar_code,
ingredients_list, allergens_contains,
allergens_may_contain)
VALUES
( '$proCode', '$proDescr' , '$proManu',
'$proCPU' , '$proWPU' , '$proBarCode',
'$proIngredients' , '$proAllergens',
'$proMayAllergens')";
//Run the insert query
if (!mysql_query($sql)) {
echo mysql_error();
}
?>
UPDATE: I removed id inserts as they are auto-increment and i learned from your answers that a null does not need to be coded and mysql looks after AI. Thanks guys!
Query need to be like:-
$sql = "INSERT INTO prodb.simplex_list
(code, description, manufacturer,
cost_per_unit, weight_per_unit,
bar_code, ingredients_list, allergens_contains,
allergens_may_contain)
VALUES ('$proCode', '$proDescr', '$proManu',
'$proCPU','$proWPU', '$proBarCode',
'$proIngredients', '$proAllergens',
'$proMayAllergens')";
Note:- please stop using mysql_*. Use mysqli_* or PDO. Also this will work only when id field must be auto incremented.

SQL - Insert INTO results in nothing

I've been trying to get this INSERT to work correctly, so I worked through the undefined variable and index problems and now I think I am nearly there.
Below is the code:
<?php
session_start();
require "../dbconn.php";
$username = $_SESSION['username'];
$query1 = "SELECT user_table.user_id FROM user_table WHERE user_table.username ='".$username."'";
$query2 = "SELECT department.department_id FROM department, user_table, inventory
WHERE user_table.user_id = department.user_id
AND department.department_id = inventory.department_id";
//Copy the variables that the form placed in the URL
//into these three variables
$item_id = NULL;
$category = $_GET['category'];
$item_name = $_GET['item_name'];
$item_description = $_GET['item_description'];
$item_quantity = $_GET['quantity'];
$item_quality = $_GET['quality'];
$item_status = NULL;
$order_date = $_GET['order_date'];
$invoice_attachment = NULL;
$edit_url = 'Edit';
$ordered_by = $username;
$user_id = mysql_query($query1) or die(mysql_error());
$department_id = mysql_query($query2) or die(mysql_error());
$price = $_GET['price'];
$vat = $_GET['vat%'];
$vat_amount = $_GET['vat_amount'];
$create_date = date("D M d, Y G:i");
$change_date = NULL;
//set up the query using the values that were passed via the URL from the form
$query2 = mysql_query("INSERT INTO inventory (item_id, category, item_name, item_description, item_quantity, item_quality, item_status, order_date,
invoice_attachment, edit_url, ordered_by, user_id, department_id, price, vat, vat_amount, create_date, change_date VALUES(
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$item_quantity."',
'".$item_quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$user_id."',
'".$department_id."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
header( 'Location:../myorders.php');
?>
Error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VALUES( '', 'adasd', 'dsadsa', 'dsad', 'sadsad', '' at line 2
Could anyone please let me know where I am going wrong? :(
Been staring at this for 3-5 hours already :(
You are not actually trying to insert any data into your table. You only craft and assign the query in string form to a variable. You need to use the function mysql_query to actually run the code.
As pointed out you will also have to specify the columns you are inserting data into in the MySQL query if you don't supply data for every column (in the correct order). Here you can look at the MySQL insert syntax.
I would also urge you to look into using the MySQLi or the MySQL PDO extensions for communicating with your MySQL database since the MySQL extension is deprecated. Look here for additional information and comparisons.
Here, you only assign the values to the $query var:
$query = "INSERT INTO inventory VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')"
or die("Error: ".mysql_error());
You do not actually run the query.
try:
$query = mysql_query("INSERT INTO inventory (column_name1, column_name 2, column_name3 ... the column name for each field you insert) VALUES (
'".$item_id."',
'".$category."',
'".$item_name."',
'".$item_description."',
'".$quantity."',
'".$quality."',
'".$item_status."',
'".$order_date."',
'".$invoice_attachment."',
'".$edit_url."',
'".$ordered_by."',
'".$price."',
'".$vat."',
'".$vat_amount."',
'".$create_date."',
'".$change_date."')")
or die("Error: ".mysql_error());
Also, you should use mysqli_* or any other PDO as the mysql_* functions are deprecated
If you are not inserting in all columns you need to specify the columns you are going to insert. Like this:
INSERT INTO Table(Column1, Column6) VALUES (Value1, Value6)
You are missing the column names in your INSERT

Check database table if row exists, then create it if not

I am trying to check the database if data for a specific date exists. If it does not exist, then a new row needs to be inserted into the database for that date. Here's my code so far in php/sql (after db login info), but I can't get it to work:
// gets two data points from form submission
$tablename = $_GET['tablename'];
$date = $_GET['date'];
//Fetching from your database table.
$query = "IF NOT EXISTS (SELECT * FROM $tablename WHERE date = $date) BEGIN Insert into $tablename (date, var1, var2) VALUES ('$date', '', ''); END"
$result = mysql_query($query);
Please HELP...
Just USE INSERT ON DUPLICATE KEY UPDATE

PHP/MYSQL - Check whether it have duplicated record before inserting new record

Suppose I have a table called "device" as below:
device_id(field)
123asf15fas
456g4fd45ww
7861fassd45
I would like to use the code below to insert new record:
...
$q = "INSERT INTO $database.$table `device_id` VALUES $device_id";
$result = mysql_query($q);
...
I don't want to insert a record that is already exist in the DB table, so how can I check whether it have duplicated record before inserting new record?
Should I revise the MYSQL statement or PHP code?
Thanks
UPDATE
<?php
// YOUR MYSQL DATABASE CONNECTION
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'device';
$table = 'device_id';
$db_link = mysql_connect($hostname, $username, $password);
mysql_select_db( $database ) or die('ConnectToMySQL: Could not select database: ' . $database );
//$result = ini_set ( 'mysql.connect_timeout' , '60' );
$device_id = $_GET["device_id"];
$q = "REPLACE INTO $database.$table (`device_id`) VALUES ($device_id)";
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Since I understood well your question you have two ways to go, it depends how you would like to do the task.
First way -> A simple query can returns a boolean result in the device_id (Exists or not) from your database table. If yes then do not INSERT or REPLACE (if you wish).
Second Way -> You can edit the structure of your table and certify that the field device_id is a UNIQUE field.
[EDITED]
Explaining the First Way
Query your table as follow:
SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'
then if you got results, then you have already that data stored in your table, then the results is 1 otherwise it is 0
In raw php it looks like:
$result = mysql_query("SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'");
if (!$result)
{
// your code INSERT
$result = mysql_query("INSERT INTO $database.$table `device_id` VALUES $device_id");
}
Explaining the Second Way
If your table is not yet populated you can create an index for your table, for example go to your SQL command line or DBMS and do the follow command to your table:
ALTER TABLE `your_table` ADD UNIQUE (`device_id`)
Warning: If it is already populated and there are some equal data on that field, then the index will not be created.
With the index, when someone try to insert the same ID, will get with an error message, something like this:
#1062 - Duplicate entry '1' for key 'PRIMARY'
The best practice is to use as few SQL queries as possible. You can try:
REPLACE INTO $database.$table SET device_id = $device_id;
Source

Categories