Inserting data into table_name as php variable - php

I am taking table name as php variable to insert data into table.
But it gives error. What's bad here?
if($flag == 1)
$table = 'frrole_pupolar_article';
else
$table = 'frrole_category_article';
$insertQuery1 = "INSERT INTO '.$table.' (`url`, `sentiment`, `category`, `title` ,`time`,`img_url`,`rt_count`,`tweet_count`) VALUES ('".$url."','".$setiment."','".$category."','".$title."','".$time."','".$img_url."','".$rt_count."','".$tweet_count."')";
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 ''.frrole_category_article.' (`url`, `sentiment`, `category`, `title` ,`time`,`im' at line 1

$insertQuery1 = "INSERT INTO '" .$table. "' (`url`, `sentiment`, `category`, `title` ,`time`,`img_url`,`rt_count`,`tweet_count`) VALUES ('".$url."','".$setiment."','".$category."','".$title."','".$time."','".$img_url."','".$rt_count."','".$tweet_count."')";
You wrongly written '.$table.' instead of '" .$table. "'

Just do
$insertQuery1 = "INSERT INTO $table (`url`, `sentiment`, `category`,
`title` ,`time`,`img_url`,`rt_count`,`tweet_count`)
VALUES ('".$url."','".$setiment."','".$category."',
'".$title."','".$time."','".$img_url."','".$rt_count."',
'".$tweet_count."')";
remove the concatenations and single quotes

If your string is $insertQuery1 = "INSERT INTO '.$table.' (url,sentiment,
You cannot escape it by using single quotes '..'
Just do double quotes:
$insertQuery1 = "INSERT INTO ".$table." (`url`, `sentiment`, ....
also for all that is holy, use damn {} for if(){} statements, not using them is poor form

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)");

database problems with php

I am trying to insert a row into my data base, but what ever i seem to do I am always getting an error.
Sometimes I get parse errors and sometimes I get column errors.
Here is my code.
Thanks in advance.
<?php
include_once('config.php');
$asin = $_POST['asin'];
// $title = "<script>document.write(title)</script>";
// $mpn = "<script>document.write(mpn)</script>";
// $price = "<script>document.write(price)</script>";
$sql = "INSERT INTO `amazon`.`amazon` (`asin`, `title`, `mpn`, `price`) VALUES ($asin, "test", 1, 2)";
// $sql = 'INSERT INTO amazon'.
// '(asin, title, mpn,price) '.
// 'VALUES ('{$asin},' "test", 1, 2)';
mysql_select_db('amazon');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
?>
You need to use '' against your variable $asin as:
$sql = "INSERT INTO `amazon`.`amazon` (`asin`, `title`, `mpn`, `price`) VALUES ('".$asin."', 'test', 1, 2)";
Note:-
You can't use double quotes in double quotes. Replace double
quote(") with single quote(') around test value.
use variables in single quotes.(Example - $asin to '$asin')
Replace your query with this:-
$sql = "INSERT INTO `amazon`.`amazon` (`asin`, `title`, `mpn`, `price`) VALUES ('$asin', 'test', 1, 2)";
You have made two mistakes. in
$sql = "INSERT INTO `amazon`.`amazon` (`asin`, `title`, `mpn`, `price`) VALUES ($asin, "test", 1, 2)";
$asin and "test".
if $asin is an integer value always THEN it's okay otherwise you have to write it '".$asin."'
and for "test" the error is the comma you use here (") because you query is starting with same (") comma, so when you put same comma before test then query ends here and give you error. So replace this comma by (').
replace "test" by 'test'.
Now correct query is -
$sql = "INSERT INTO `amazon`.`amazon` (`asin`, `title`, `mpn`, `price`) VALUES ('".$asin."', 'test', 1, 2)";

error in mySQL syntax

What's wrong in this SQL query ?!
if(isset($_POST['submit'])){
$name = $_POST['name'];
$author = $_POST['author'];
$pub = $_POST['pub'];
$sibn = $_POST['sibn'];
$year = $_POST['year'];
$version = $_POST['version'];
$desc = $_POST['desc'];
$selected_db = mysql_select_db("bookstore",$con);
$query = "INSERT INTO introducebook (name, author, pub, sibn, year, version, desc) VALUES ('{$name}', '{$author}', '{$pub}', '{$sibn}', {$year}, {$version}, '{$desc}');" ;
$result = mysql_query($query,$con);
if(!$result){die('could not perform query'.mysql_error());}
echo mysql_affected_rows();
}
?>
the error is (I pass all inputs test):
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 'desc) VALUES ('test', 'test', 'test', 'test', test, test, 'test')' at line 1
You need to escape reserved words in MySQL like desc with backticks
INSERT INTO introducebook (name, ..., `desc`) VALUES ...
to pass plain text you need brackets, this will be correct
INSERT INTO introducebook (`name`, `author`, `pub`, `sibn`, `year`, `version`, `desc`) VALUES ('{$name}', '{$author}', '{$pub}', '{$sibn}', '{$year}', '{$version}', '{$desc}')
and yes, you also need backticks.

what causes the error with this mysql query?

mysql_query ("
INSERT INTO items
(index, name, description, given_by,
cost_to_tcs, starting_bid, auction_type)
VALUES
('{$index_number}','{$name}','{$description}','{$donated_by}',
NULL,'{$auction_type}','{$starting_bid}')
")
or die("3: " . mysql_error());
Errors with:
3: 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 ''index', 'name', 'description', 'given_by', 'cost_to_tcs', 'starting_bid', 'auct' at line 1
Thanks for any help.
index is mysql Reserved keyword, wrap index with (back tick) `` `
INSERT INTO items
(`index`, `name`, `description`, `given_by`,
`cost_to_tcs`, `starting_bid`, `auction_type`)
Reserve key words
try like that:
mysql_query ("
INSERT INTO items (
`index`,
`name`,
`description`,
`given_by`,
`cost_to_tcs`,
`starting_bid`,
`auction_type`)
VALUES(
'$index_number',
'$name',
'$description',
'$donated_by',
NULL,
'$auction_type',
'$starting_bid')
")
or die("3: " . mysql_error());
also make sure to safe the data with mysql_real_escape_string();

MySQL Insert syntax error - Cant find it!

There's gotta be something small I keep missing here, but I can't find it for the life of me.
$insert = mysql_query("INSERT INTO USERS
(`FBID`, `FIRST_NAME`, `LAST_NAME`, `GENDER`)
VALUES ('$fbid', '$firstName', '$lastName', '$gender')");
The error is:
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 '1' at line 1
Any ideas?
You are not having variables correctly escaped. Use mysql_real_escape_string and code like this:
$insert = mysql_query("INSERT INTO USERS (`FBID`, `FIRST_NAME`, `LAST_NAME`, `GENDER`)
VALUES (
'".mysql_real_escape_string($fbid)."',
'".mysql_real_escape_string($firstName)."',
'".mysql_real_escape_string($lastName)."',
'".mysql_real_escape_string($gender)."'
)");
If the variables contain any quotes, they create the problem if you don't properly escape them.
Do any of your names contain single quotes?
Try writing out the value of the query to log/console/debug to ensure that it's what you expect.
Try wrapping your variables in {}.
'{$fbid}', '{$firstName}', '{$lastName}', '{$gender}'
Otherwise you are going to have to use string concatenation.
'".$fbid."','".$firstName."','"...
I'm assuming your variables already contain proper escaped data.
Try doing it like this:
$sql = <<EOL
INSERT INTO USERS (`FBID`, `FIRST_NAME`, `LAST_NAME`, `GENDER`)
VALUES ('$fbid', '$firstName', '$lastName', '$gender')
EOL;
$stmt = mysql_query($sql) or die("MySQL error: " . mysql_error());
This will preserve the query for you in $sql so you can echo it out elsewhere and see what was actually produced.

Categories