inserting values into table fails - php

function db_insert_article($flag,$url,$sentiment,$category,$title,$time,$rt_count,$tweet_count,$img_url)
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$insertQuery1 = "INSERT INTO frrole_popular_article (`url`, `sentiment`, `title` , `time` , `img_url` , `rt_count` , `tweet_count`, `today`) VALUES ('".$url."','".$sentiment."','".$title."','".$time."','".$img_url."','".$rt_count."','".$tweet_count."','".$today."')";
if (!mysqli_query($con,$insertQuery1))
{
//die('Error: ' . mysqli_error($con));
}
}
TAble structure:
Everything looks alright. Then why it does not insert into table? below this I have other queries which inserts into table successfully. IT also does not show any error.
UPdate1 : This query works fine which is just below above code
$insertQuery2 = "INSERT INTO frrole_article_sentiment (`url`, `sentiment`, `category`, `title` , `time` , `img_url` , `rt_count` , `tweet_count`, `today`) VALUES ('".$url."','".$sentiment."','".$category."','".$title."','".$time."','".$img_url."','".$rt_count."','".$tweet_count."','".$today."')";
if (!mysqli_query($con,$insertQuery2))
{
//die('Error: ' . mysqli_error($con));
}
UPDATE2
$insertQuery1 = "INSERT INTO frrole_popular_article (`url` , `sentiment`, `img_url` , `title` , `rt_count` , `tweet_count`, `time` , `today`) VALUES ('".$url."','".$sentiment."','".$img_url."','".$title."','".$rt_count."','".$tweet_count."','".$time."','".$today."')";

you are trying to insert with:
$insertQuery2 = "INSERT INTO frrole_article_sentiment
(`url`, `sentiment`, `category`,
`title` , `time` , `img_url` ,
`rt_count` , `tweet_count`, `today`)
VALUES ....
but when you make select * from frrole_article_sentiment; it returned you 8 columns and you are trying to insert in 9 columns, in other words in your state insert into.... you are trying to insert into CATEGORY attribute but it doesn't exist in the table

Related

PHP MySQL Not inserting any data. No errors [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
I'm not sure why it's not inserting any data.
No errors are returned.
I'm new in the mysql scene so i might be doing something wrong..
Do you guys mind pointing me towards the right direction?
$link = mysqli_connect("localhost", "root", "", "testdatabase");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
else if ($command == 'create-key'){
$keys = $_GET['nkey'];
if (empty($_GET['nkey'])){
print('Error: No key specified to create!');
die();
}
print ('Key '. $_GET['nkey'] .' has been created.');
$sql = ("INSERT INTO `keys` (`key`, `status`) VALUES ('. $keys .', 0)");
}
SQL Code:
CREATE TABLE `keys` (
`key` varchar(15) NOT NULL,
`status` int(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
There is no need of ()
Change Query From
$sql = ("INSERT INTO `keys` (`key`, `status`) VALUES ('. $keys .', 0)");
To
$sql = "INSERT INTO `keys` (`key`, `status`) VALUES ('$keys', 0)";
And then Execute this Query
You'll probably need this on top of your script to see PHP errors:
<?php
ini_set('display_errors', 'on');
error_reporting ( E_ALL );
To help you with your error, have a look at your query.
$sql = ("INSERT INTO `keys` (`key`, `status`) VALUES ('. $keys .', 0)");
While this is should insert . $keys . in your table, please try:
$sql = ("INSERT INTO `keys` (`key`, `status`) VALUES ('". $keys ."', 0)");

Query work in PhpMyAdmin but does not work in php codes

i wrote a code that insert in two table in one time that tables connect with each other with foreign key .
i search in this site but did not find an answer .
this query worked in phpmyadmin but have false answer in php code and does not work in php ....why??? :(
this is my Query and code in php.... please help me
INSERT INTO `interviewdeliverytable` ( `FirstName` , `LastName` , `PhoneNumber` , `PostCode` , `IdNumebr` , `BirthDate` , `Address` , `Accepted` , `IsBike` , `Date` )
VALUES ('$FirstName', '$LastName', '$PhoneNumber', '$PostCode', '$IdNumber', '$BirthDate', '$Address', '$Accepted', '$IsBike', '$Date');
SELECT #Var := Last_INSERT_ID() ;
INSERT INTO `interviewbiketable` (`PhoneNumber` , `DriverLicenseId` , `BikeModel` , `PelakNumebr` ,`Accepted`,`IsBike`, DeliveryId )
VALUES ('$PhoneNumber', '$DeliverLicenseId', '$BikeModel', '$PelakNumber','$Accepted','$IsBike', #Var)
php codes
function registerDelivery(){
$connection=createConnection();
if(!$connection){
echo "Error";
}else{
//
//get objects
//
$json = file_get_contents('php://input');
$obj = json_decode($json);
$FirstName=$obj->FirstName;
$LastName=$obj->LastName;
$PostCode=$obj->PostCode;
$IdNumber=$obj->IdNumebr;
$BirthDate=$obj->BirthDate;
$Address=$obj->Address;
$Accepted=$obj->Accepted;
$IsBike=$obj->IsBike;
$Date=$obj->Date;
$DeliverLicenseId=$obj->DriverLicenseId;
$BikeModel=$obj->BikeModel;
$PelakNumber=$obj->PelakNumebr;
$PhoneNumber=$obj->PhoneNumber;
//
//insert Query
//
$result=mysqli_query($connection,"INSERT INTO `interviewdeliverytable` ( `FirstName` , `LastName` , `PhoneNumber` , `PostCode` , `IdNumebr` , `BirthDate` , `Address` , `Accepted` , `IsBike` , `Date` )
VALUES ('$FirstName', '$LastName', '$PhoneNumber', '$PostCode', '$IdNumber', '$BirthDate', '$Address', '$Accepted', '$IsBike', '$Date');
SELECT #Var := Last_INSERT_ID() ;
INSERT INTO `interviewbiketable` (`PhoneNumber` , `DriverLicenseId` , `BikeModel` , `PelakNumebr` ,`Accepted`,`IsBike`, DeliveryId )
VALUES ('$PhoneNumber', '$DeliverLicenseId', '$BikeModel', '$PelakNumber','$Accepted','$IsBike', #Var)");
echo json_encode(array('Result'=>$result));
mysqli_close($connection);
}
}
This is not a query but a set of multiple queries. Therefore you have to run them separately one by one:
mysqli_query($connection,"INSERT INTO ...");
$id = mysqli_insert_id($connection);
mysqli_query($connection,"INSERT INTO ...");
Note that you should be using prepared statements for your queries.
thanks all
i Edited my Queries...
function registerDelivery(){
$connection=createConnection();
if(!$connection){
echo "Error";
}else{
//
//get objects
//
$json = file_get_contents('php://input');
$obj = json_decode($json);
$FirstName=$obj->FirstName;
$LastName=$obj->LastName;
$PostCode=$obj->PostCode;
$IdNumber=$obj->IdNumebr;
$BirthDate=$obj->BirthDate;
$Address=$obj->Address;
$Accepted=$obj->Accepted;
$IsBike=$obj->IsBike;
$Date=$obj->Date;
$DeliverLicenseId=$obj->DriverLicenseId;
$BikeModel=$obj->BikeModel;
$PelakNumber=$obj->PelakNumebr;
$PhoneNumber=$obj->PhoneNumber;
//
//insert Query
//
$result=mysqli_query($connection,"INSERT INTO `interviewdeliverytable` ( `FirstName` , `LastName` , `PhoneNumber` , `PostCode` , `IdNumebr` , `BirthDate` , `Address` , `Accepted` , `IsBike` , `Date` )
VALUES ('$FirstName', '$LastName', '$PhoneNumber', '$PostCode', '$IdNumber', '$BirthDate', '$Address', '$Accepted', '$IsBike', '$Date');");
if($result){
printf ("New Record has id %d.\n", $connection->insert_id);
$id=$connection->insert_id;
if($id!=null){
$resFinall=mysqli_query($connection,
"INSERT INTO `interviewbiketable` (`PhoneNumber` , `DriverLicenseId` , `BikeModel` , `PelakNumebr` ,`Accepted`,`IsBike`, DeliveryId ) VALUES ('$PhoneNumber', '$DeliverLicenseId', '$BikeModel', '$PelakNumber','$Accepted','$IsBike', '$id');");
echo json_encode(array('Result'=>$resFinall));
}}
it worked and insert all data in two tables ...thanks alot

Not inserting into database sql read error

<?
include("../../panel/inc/config.php");
$ip = $_SERVER['REMOTE_ADDR'];
// Insert the log
$insert = "INSERT INTO logs (log, ip, date) VALUES ('{$log}', '{$ip}', '{$date}')";
mysql_query($insert) or die("MySQL Error - Could not insert reviews");
$date = date("d/m/y - h:ia");
$insertLog = "INSERT INTO `logs` ( `log` , `ip`, `date` ) VALUES ('viewed test page', '$date')";
mysql_query($insertLog) or die('MySQL Error - Could not insert a log.');
?>
basically when someone views this page, I want it to insert into the database, but it's not inserting. I get the Error for inserting log.
Any ideas?
My database is
$insertLog = "INSERT INTO `logs` ( `log` , `ip`, `date` ) VALUES ('viewed test page', '$date')";
missing one column value here. You have three columns but two values in above query. It seems that you have missed ip value in above query.
you should try like this:
$ip = $_SERVER['REMOTE_ADDR'];
if(isset($ip)){
// Insert the log
$insert = "INSERT INTO logs (log, ip, date) VALUES ('{$log}', '{$ip}', '{$date}')";
mysql_query($insert) or die('MySQL Error - ' . mysql_error() );
$date = date("d/m/y - h:ia");
$insertLog = "INSERT INTO `logs` ( `log` , `ip`, `date` ) VALUES ('viewed test page','$ip' '$date')";
mysql_query($insertLog) or die('MySQL Error - ' . mysql_error() );
}
notice: all mysql_* functions are deprecated. You should move to PDO or mysqli.

php mysql execute 2 insert statements based on first insert ID

This is what I am able to do:
When a user fills out a form to sign up the script will insert sign up info into table ps_reg_users. This table contains basic profile information.
I have added a Badge/Achievement section to display badges based on certain criteria.
What I need to do:
Once the user signs up, add that user to another table ps_badges with the id from the first query.
The id is set to auto increment on table ps_reg_users and inserts NULL upon submit, thus assigning the next id.
How would I INSERT a query to ps_reg_users then retrieve the id after it creates it to make another query based on that id?
PHP
$query = "INSERT INTO `" . DB_PREFIX . "reg_users` ( `id` , `first_name` , `last_name` , `password` , `email` , `date_time` , `user_status`, `verify_code` , `reward_points`, `ref_user`)
VALUES (NULL , '$first_name', '$last_name', '$password', '$e_email', '$date_time' , 'y', '$verify_code', '0' , '$ref_uid')";
This ^ works.
I need to execute this right after
$query = "INSERT INTO `" . DB_PREFIX . "badges` ( `user_id` , `pts_reputation` , `pts_comments` , `pts_uploads` , `pts_downloads` , `pts_featured` , `pts_activity`, `pts_refer`, `pts_donator` , `pts_country`)
VALUES (NULL , '0', '0', '0', '0', '0', '0', '0', '0', NULL)";
I hope im not over explaining, I think I need to tap into LAST_INSERT_ID() but how would I get it from the first query?
Basic sequence:
$sql = "INSERT ....";
$result = mysql_query($sql) or die(mysql_error());
$id = mysql_insert_id();
$sql = "INSERT .... (id,...) VALUES ($id, ...);"
$result = mysql_query($sql) or die(mysql_error());
Of course, you're still using an obsolete interface and SHOULD be switching to mysqli or PDO.
mysql_insert_id(); mysql function returns last inserted id

Insert statement with automatically generated columns

I want to create an INSERT statement using the columns of my table and NULL or blank values for the content except for the id, created_by .etc. I am trying to avoid duplicates. Right now I get:
INSERT INTO testimonials (id, created, created_by, id, quote, name, position, company, published, created, created_by, last_modified_by, last_modified) VALUES ('257927816', NOW(), '1', '')
and I would like to have blank values iterate in the VALUES section for everything but the first 3, which I define.
function insertBlankWithID($table, $postFxn) {
global $randomID;
$id = $randomID;
$resultInsert = mysql_query("SELECT * FROM " . $table);
if (!$resultInsert) {
echo '<div class="ec-messages messages-error">'.QUERY_ERROR.'</div>';
include($cmsdir . FOOTER_EXIT);
exit();
}
$columns = array();
while ($row = mysql_fetch_assoc($resultInsert)) {
if (empty($columns)) {
$columns = array_keys($row);
}
}
//$sql = 'INSERT INTO `testimonials` (`id`, `quote`, `name`, `position`, `company`, `published`, `created`, `created_by`, `last_modified_by`, `last_modified`) VALUES ('.$id.', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);';
$sql = sprintf("INSERT INTO %s (id, created, created_by, %s) VALUES ('".$id."', NOW(), '".$_SESSION['user_id']."', '%s')", $table, implode(', ', $columns), implode("', '", ''));
mysql_query($sql);
/*
if (!$sql) {
echo '<div class="ec-messages messages-error">'.QUERY_ERROR.'</div>';
exit();
}
*/
echo $sql;
}
// redirect(basename($_SERVER['PHP_SELF'], ".php").'?s=output&id='.$id
insertBlankWithID('testimonials', $postFxn);
Looking at your code, you should limit the select to 1, (ie $resultInsert = mysql_query("SELECT * FROM " . $table. " limit 1"); as you don't need the information, just the keys. That removes the need for the while loop.
Now, to get all the keys except the first three, for your $columns variable, use array_slice such as $columns = array_slice($columns, 3); Or, if it isn't the first three when you select *, you can do $columns = array_diff($columns, array('id', 'created', 'created_by') );
Now, to insert null after the first three, you are imploding a string - which won't work, instead you can make an array of null values matching the count of the new $columns such as:
$blanks = array_fill(0, count($columns), 'null');
and when creating your statement, do implode(", ", $blanks), which would make your $sql look like:
$sql = sprintf("INSERT INTO %s (id, created, created_by, %s) VALUES ('".$id."', NOW(), '".$_SESSION['user_id']."', '%s')", $table, implode(', ', $columns), implode(", ", $blanks));
And that should fix the issue you've described.
Also, while I'm here, it should be noted that you should not use mysql_ functions anymore and move to mysqli_ for the same type of procedure-oriented MySQL access.

Categories