php adding wrong value to mySql database - php

i have built an air for android app that posts content to facebook and on success sends a url query to a php file to add the post id of the content along with fb_id and the users name. the problem is it is not adding the value i am giving it it is instead adding the same number(dont know where it is coming from) to the post_id and fb_id. i know the right values are being sent by the mobile app.
php:
<?php
/*
------------variables set in flash--------------
videoVars.postId = result.id
videoVars.uid = uid //fb user id
videoVars.firstName = firstName
videoVars.lastName = lastName
*/
$postId = $_REQUEST['postId'];
$uid = $_REQUEST['uid'];
$firstName = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
echo $postId.'<br/>';
echo $uid.'<br/>';
echo $firstName.'<br/>';
echo $lastName.'<br/>';
//connect to database
include('db-connect.php');
$addVideo = mysqli_query($dbc , "INSERT INTO content (content_id, post_id, fb_id, first_name, last_name ) VALUES('','".$postId."','".$uid."','".$firstName."','".$lastName."')");
?>
the value i am getting for post_id and user_id are the same even though they should be different. i manually typed the vars in to addressbar in browser and it still misbehaved in the same way. the only way i can add more than one row is to add it in the sql tab of phpMyAdmin

If your echo calls output the correct values, check your database table structure and make sure there's no UNIQUE key set for fb_id.
Then, make sure you're escaping all your content with mysqli_real_escape_string ( mysqli $link , string $escapestr ). http://ca3.php.net/manual/en/mysqli.real-escape-string.php
Is content_id an auto_increment value? If so, try passing NULL for it, without the single quotes, instead of an empty string.
To debug, you can also try echoing your query (first assign it to a variable $sql = "[QUERY HERE]";, then pass the variable to the function, then echo the $sql variable and finally call your file manually.

I guess that you have problem on content_id field. it should has auto_increment property.
In your sql, when you inserts content_id as a blank value '' it will convert to 0, next time when you insert a blank value again you will has "Duplicate entry '0' for key 'PRIMARY'" message.
to fix it just remove the primary key field in your query
i.e:
$addVideo = mysqli_query($dbc , "INSERT INTO content ( post_id, fb_id, first_name, last_name ) VALUES('".$postId."','".$uid."','".$firstName."','".$lastName."')");
Or you can insert a null value for it:
$addVideo = mysqli_query($dbc , "INSERT INTO content (content_id, post_id, fb_id, first_name, last_name ) VALUES(null,'".$postId."','".$uid."','".$firstName."','".$lastName."')");
You can try to print out your current - wrong sql error like this:
$addVideo = mysqli_query($dbc , "INSERT INTO content (content_id, post_id, fb_id, first_name, last_name ) VALUES('','".$postId."','".$uid."','".$firstName."','".$lastName."')");
if (!$addVideo) {
printf("Error: %s\n", mysqli_error($dbc));
}

The problem is the id were being stored as ints in the database and the biggest allowable int value is 2147483647 which is being put in each time and as the numeric ids are bigger numbers than 2147483647 and one of the fields is set to unique it can only add one row. i have changed the type to bigint and it is working fine now. i have also implemented some of # dAngelov suggestions.

Related

Insert Multiple Value into table MySQL if not exists

I have a table with 3 columns (ID, username, full name), I want the ID to be AUTOINCREMENT. I want to insert into the table only if it does not already exist in the table.
This is my Code:
$fullName = $_POST['fullname'];
$username = $_POST['username'];
$dbhost = "localhost";
$dbname = "databasename";
$dbusername = "root";
$dbpassword = "";
$link = new PDO("mysql:host=$dbhost;dbname=$dbname","$dbusername","");
$statement = $link->prepare('INSERT INTO accounts (username, fullname)
VALUES (:username, :fname)');
$statement->execute([
'fname' => $fullName,
'username' => $usernameget,
]);
If your id is already autoncrement then you no need to mention in query.
You can simply write below query
insert into accounts (username,fullname) values( $username , $fullname )
you can do this with if else condition in PHP
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$chk = mysqli_query("select * FROM `accounts` where fullname='$fullname' and username='$username'");
$rs = mysqli_fetch_array($chk);
if($rs == "")
{
$ins = mysqli_query("INSERT INTO `accounts`(fullname,username) VALUES ('$fullname','$username'))";
}
else{
echo "Duplicate entry";
}
or you can do this by SQL Query also.
INSERT INTO accounts(username,fullname)
SELECT * from (SELECT '$username', '$fullname') AS tmp
WHERE NOT EXISTS
(SELECT username FROM accounts WHERE username='$username')
There's several things to fix here.
Don't specify column values if you don't need to, or don't care about the value. Only specify if necessary or relevant. In this case id should be omitted.
Always use placeholder values for your user data. Never put $_GET or $_POST data directly in a query.
To avoid duplication add a UNIQUE constraint on the table.
To fix that you do adjust your code:
// Enable exceptions, avoiding the need for manual error checking
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Try and keep the order of things like this consistent through your code
$username = $_POST['username'];
$fullname = $_POST['fullname'];
// Here using a short, common name for the database handle $db
$db = new mysqli("localhost","root","","database");
// Prepare your insert first as a query with no data, only placeholders
$db->prepare("insert into accounts (username,fullname) values(?,?)");
// Bind the data to the placeholders, here two string ("s") values.
$db->bind_param('ss', $username, $fullname);
// Execute the query
$db->execute();
To add the UNIQUE constraints use CREATE INDEX:
CREATE INDEX idx_accounts_username (username);
CREATE INDEX idx_accounts_full_name (full_name);
That has to be run in your MySQL shell, not PHP.
When a UNIQUE constraint is in place MySQL will not allow duplicate data. Note that NULL values don't count, and can be "duplicated". Set NOT NULL on your columns to force them to be completely unique.
As your id is autoincrement primary key, so you can create or update it with:
insert into accounts (username,fullname) values( $username , $fullname ) on duplicate key update username = '$username',fullname = '$fullname'
To get correct answers, a question must be asked with as much explanation as possible. you should atleast tell what have you done and then what are you getting.
As far as i have understood, to achieve your goal, the table structure must be changed and inserting query also.
Remember to accept the answer and click the upvote button if the answer satisfies you,else give more information in the question, so that members here, can give right answers.
If you understand table creating queries go to bottom of this answer or else do as follows:
if you use gui to create table,
1. click on create new table.
2. in the right pane give table name and column names as shown. (dont give space in 'full name' instead give 'full_name' or 'fullname')
3. scroll the winow to the right till you see A_I column as shown.
4. tick the first line (which we have used as id), 'add index' box will appear.
just click here go (at the bottom).
you will be redirected to table list as shown.
6. open (click) your table again.
7. click on structure.
now suppose you don't want duplicates in 'username' column, click this column and click on 'unique' as shown
if you don't want duplicate when both the columns' value together, click both the columns and then click 'unique' as shown
if you understand create table commands:here is the sql for above:
CREATE TABLE accounts (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(25) NOT NULL,
fullname varchar(55) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY username (username)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
with above table structure records will be autoincremented and duplicate names will not be added. (remember to handle duplicate entries error in you inserting querie withINSERT IGNORE INTOwith this your query will be:
$statement = $link->prepare('INSERT IGNORE INTO accounts (username, fullname)
VALUES (:username, :fname)');
or you can also useON DUPLICATE KEY)
First set your primary key (eg. id) if not set as auto increment
Second use multiple insertion value
INSERT IGNORE INTO accounts (username,fullname) VALUES ("p","k"),("c","s");
IGNORE keyword is use to duplicate
IF you want to see with PDO

prevent duplicate records in mysql table

Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.

Last insert id value store to same table another specific column

i had following table and columns
Table Name = users
column = user_id, name, email, password, status, identity
i'm using following query for insert data to table users
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['name']);
$password = mysql_real_escape_string($_POST['txtPassword']);
$password = md5($password); //===Encrypt Password
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0')";
$res = mysql_query($query);
header('location:success_register.php');//Redirect To Success Page
}
what i am asking is, i want store last id to column identity also
for example: if last user_id= 10, identity also will be = 10. i mean get last id then store that id to identity column
Result will be look like this
user_id name email password status identity
5 aa aaa#ab.com **** 1 5
6 bbb bbb#ac.com **** 1 6
how to do it,?
In MYSQL, you have alternative possibility to find it, when you think last_insert_id() is not working. You may require to have SELECT privilege on INFORMATION_SCHEMA and its tables.
If you have that privileges, try the following query.
$query = "insert into users( name, email, pasword, status, identity )"
. " values( '$name', '$email', '$password', '1',"
. " ( SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES"
. " WHERE TABLE_NAME='users' and TABLE_SCHEMA=DATABASE() )"
. " )";
And, lastly, suggesting to stop using deprecated API.
Save last insert id like this:
$id = mysql_insert_id();
and use it in next insert
You are looking for:
mysql_insert_id()
mysqli_insert_id(mysqli $link)//for mysqli
PDO::lastInsertId()//for PDO
Other Approach:
if your id column is auto increment and not random then you can select the max id(everytime just after your insert query) from the users table and insert it into whatever column you want.
$id=mysql_result(mysql_query(select max(user_id)
from users),0);
Dont use mysql_ as they are depracated.*
here is what you are looking for. Select max(user_id)+1 and store it in a variable.
Now you need to pass this variable in user_id and identity parameter.
Note that even though user_id is auto increment, it will allow you to insert the new row with specified user_id
i think you can also put it like this
$lastID = MySQLI_insert_id($DBcon); //where Dbcon is your connection to your database
and then
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','$lastID')";
$res = mysql_query($query);
I think you need to insert number of rows in the table after the insert:
It may useful to you
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0',(select COUNT(*)+1 FROM users))";

I cannot get default in sql to work

I am having an issue with sql right now; I have gave a value a default so if the field is left empty when the user submit, but it is not working. When the user submits an empty field to leave a comment instead of it default to anon it does nothing. Also, in the datebase the field is empty.
name VARCHAR (50) default 'anon',
$name= $_POST['name'];
$title= sha1($_POST['title']);
$texts= $_POST['texts'];
$forum_id = $_POST['forum_id'];
$name = str_replace("'","''",$name);
$title = str_replace("'","''",$title);
$title = str_replace("b074acd521","STREAMER",$title);
$texts = str_replace("'","''",$texts);
$title = substr($title,0,8);
$sql = "INSERT INTO post (name,title, texts, forum_id) VALUES ('$name', '$title', '$texts', '$forum_id')";
mysqli_query($conn1, $sql) or die('Error inserting to database.');
mysqli_close($conn1);
header('Location: requests.php');
Is there another way to do it or am I just doing something wrong?
The SQL query your using will not insert the default value from your database because you are specifying a value for name (even if that value is an empty string, or null) :
$sql = "INSERT INTO post (name,title, texts, forum_id) VALUES ('$name', '$title', '$texts', '$forum_id')";
Instead if you want the default value to be inserted into the name field you must not specify the name column in the insert statement :
$sql = "INSERT INTO post (title, texts, forum_id) VALUES ('$title', '$texts', '$forum_id')";
In SQL query you can specify for which fields, values will be provided in the query and remaining fields from the table would contain default value (in case of AUTO_INCREMENT, the next integer value will be used).
Where you given the default value directly applied in SQL? the value left in DB ultimately is what exactly you passed to DB server by SQL way, or just you defined a variable where if it don't accept a value from user then use the default value instead, please try to debug this to insure the value was handled correctly.
while insert the values you shouldn't give the column which you set default value
below Example explain it...Try like this...
create table er(id int,name char(10),gender char(2)default 'M')
Here i took gender as default
now i insert the values
insert into er (id,name)values(1,'poda')
select * from er

Insert new row in a table and auto id number

I want to insert a new row in my table. I want the id to be generated right automatically and not asked from the user. The user only provides title and text. I wrote this code in PHP:
<?php
$hostname = "localhost";
$database = "mydb";
$username = "myuser";
$password = "mypsw";
$link = mysql_connect( $hostname , $username , $password ) or
die("Attention! Problem with the connection : " . mysql_error());
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_query("SET NAMES ‘utf8’",$link);
mysql_select_db("mydb", $link);
$lastid=mysql_insert_id();
$lastid=$lastid+1;
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
if (!mysql_query($sql,$link))
{
die('Error: ' . mysql_error());
}
mysql_close($link);
header("Location: announcement.php");
?>
Sadly when I test it on my website, I get this error:
Error: Duplicate entry '0' for key 'PRIMARY'
Is mysql_insert_id() not working? What is wrong?
Don't do this. mysql will happily create an auto_increment column for you:
CREATE TABLE x (
id int not null primary key auto_increment
^^^^^^^^^^^^^^---add this to your PK field
);
INSERT INTO x (id) VALUES (null); // creates id = 1
INSERT INTO x (id) VALUES (null); // creates id = 2
mysql_insert_id() only returns the last id created by the CURRENT connection. You haven't inserted any data yet when you first run it, so you get back nothing.
Your version is incredibly vulnerable to race conditions. There is NO guarantee that the last ID you retrieve with mysql_insert_id() will not ALSO get retrieved by another copy of the script running in parallel, and get sniped out from under this copy of the script.
The primary key column on announcements should be auto_increment. When you do mysql_insert_id() it retrieves the id from the last query executed from that connection.
Because the INSERT is the query you are currently performing, it errors.
Try
INSERT INTO announcements
(date_field, title, text)
VALUES (CURDATE(),'$_POST[title]','$_POST[text]')
Just replace 'date_field', 'title', and 'text' with the applicable column names.
Alternatively the following should also work, as a NULL value in the AutoIncrement value should be acceptable
INSERT INTO announcements VALUES (NULL,CURDATE(),'$_POST[title]','$_POST[text]')
As mentioned in the other suggestion posted, you should make sure that the primary key field of the announcements table is set to be auto_increment.
Just for completion, you would use mysql_insert_id() when you want to use the id for the row you just inserted, i.e. if you then want to select the row you just inserted you could do
'SELECT * FROM announcements WHERE id = '.mysql_insert_id()
The problem is that you are asking for last insert id and you didn't inserted anything.
Convert your ID field in db to be autoincrement if its not.
Insert into database your announcment
Then ask for id using mysql_insert_id to get it.
But I see that you are not using it only when inserting then you don't need that functionality anyhow. Just insert without ID like this
"insert into announcements (InsertDate, Title, Text) VALUES (CURDATE(), '$_POST[title]', '$_POST[text]')";
and you should really be careful with your queries when using values from $_POST or $_GET or any other user typed value. There is possibility to execute SQLInjection through your form fields, so I suggest you to use mysql escape command or use parameters.
I hope this helps.
Assuming your table is set up properly, with the id field as AUTO_INCREMENT, you just need to perform an INSERT where you do not specify a value for id. That means you must specify the names of the columns you are inserting. So this line:
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
becomes this
$sql="INSERT INTO announcements (`date`,`title`,`text`) VALUES (CURDATE(),'$_POST[title]','$_POST[text]')";
I guessed what your column names might be. Obviously they need to match your table definition.
If you do this, then the mysql_insert_id() function will return the id of the row you just inserted. (That is, it gives you the value of the previous insert, not the next one.)
You probably want to add "auto increment" to the table when creating it.
This will add an id automatically when inserting something.
e.g.
CREATE TABLE announcements
(
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
some_date int(11),
title varchar(200),
text varchar(3000)
);
mysql_insert_id "Retrieves the ID generated for an AUTO_INCREMENT column by the previous query " - http://php.net/manual/en/function.mysql-insert-id.php

Categories