I'm trying to upload data to a existing User database I have stored online. I need to post the user phone number string in the user specified row. Using android and php, is there any way to post extra info in an existing row?
I think I'm not choosing WHERE to put that extra info.
<?php
require "indioPhP.php";
$username = $_POST["username"];
$phoneNumber = $_POST["phoneNumber"];
$statement = mysqli_prepare($con, "SELECT * FROM User WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
$sql ="insert into User values('$phoneNumber')";
if(mysqli_query($con,$sql)){
echo "Gracias por registrarte!";
} else{
echo "error in insertion".mysqli_error($con);
}
?>
Ok now i see your Problem:
Update User set phonenumber=? where username=?
You Need something like this ? it's only one query where you search the user and Change it. Try to read more about SQL. Your code Looks a bit confused, with prepared Statements and normal statments in the same block.
Edit:
The statement insert adds a new line in the table wheras update modifies an existing one. Assuming your table User has 4 columns: username, firstname, lastname, phonenumber, for insert, the syntax is either
insert into user values("jdoe", "John", "Doe", "555 7565")
or
insert into user(username, phonenumber) values ("jdoe", "555 7565")
In the first case, as columns are not specified, you must give all of them.
In the second case, you insert a new line specifying only some columns. The other ones will take their default values. If a missing column doesn't have a default value, you will have an error.
Related
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
everyone, I have a hard time to understand what is going on. I'm new on OOPS and wanted to add a record to my database. I have a class customer and in that class, I have a function create() that makes a new record and insert into DB. My connection is working, I instantiate(hope that is the right term) that function and then I call create().
$costumer = new Customer($args);
$date = date("Y-m-d");
$result = $costumer->create("Nome", "Cognome", 2, "email3#email.com", "12", "address", 00133, "payment", $date, "male");
public function create($first_name, $last_name, $phone_number, $email, $codice_fiscale, $adress, $cap, $payment, $data_of_join, $genre) {
$sql = "INSERT INTO costumers (first_name, last_name, phone_number, email, codice_fiscale, adress, cap, payment, data_of_join, genre)
VALUES ('$this->first_name','$this->last_name','$this->phone_number','$this->email','$this->codice_fiscale','$this->adress','$this->cap','$this->payment','$this->data_of_join','$this->genre')";
$result = self::$database->query($sql);
if(!$result) {
echo self::$database->error;
echo self::$database->errno;
}
return $result;
}
going to my page to see if I get any result. I have Incorrect integer value: '' for column 'phone_number' at row 11366.
My database fields are: -
ID
first_name
last_name
phone_number
email
codice_fiscale
adress
cap
payment
data_of_join
genre
Really don't know what is the problem. I made the same thing but in procedural same SQL and everything works just fine.
Your code is open to SQL injection related attacks. Please learn to use Prepared Statements
Now, in this case, you do not need to use $this-> to use the variables. $this is used when the variables are accessible class members. However, in your cases, these are function parameters.
In the current code, you can change the SQL string as follows:
$sql = "INSERT INTO costumers (first_name, last_name, phone_number, email, codice_fiscale, adress, cap, payment, data_of_join, genre)
VALUES ('$first_name','$last_name','$phone_number','$email','$codice_fiscale','$adress','$cap','$payment','$data_of_join','$genre')";
This is a wild guess because you haven't told us the data types of your columns.
It looks like your phone_number column is represented in your database by an integer. You Can't Do Thatâ„¢. Many telephone numbers furnished by users with spaces or punctuation.
Read this: phone number should be a string or some numeric type that have capacity to save phone number?
I need to do something like that:
SELECT id FROM table WHERE option='1' ORDER BY time LIMIT 1
then with the id in $id
UPDATE table SET used='1' WHERE id='$id'
The problem is that this way another user can update the same record in the same time.
Is there a way to do that in one only operation ?
Thanks
UPDATE table SET used='1'
WHERE id=
(SELECT id FROM
(SELECT id FROM table
WHERE option='1'
ORDER BY time
LIMIT 1) AS tmptable
)
You need to use a three step query if you have concurrent access to the same row by different users.
First query has to reserve the row for a certain user (using a dedicated field).
Second query has to check if the row reservation is for that certain user.
Third query updates the row knowing there's no collision as that user reserved it.
Between step #1 and #2, multiple users can try to grab edit access to the row but in the end only one succeeds. The ones that failed will not reach step #3.
PS: This might be overkill for your needs but it's the best way to ensure multiple users work on tasks (rows) concurrently.
PPS: Or just combine the queries into a single one as another answer points out. But if your update requires some work done, it's best to decide upfront who will do the work before updating the value.
You could use: http://php.net/manual/en/mysqli.insert-id.php
mysql_insert_id
Finds the last id updated or set and stores it. We then check to make sure the last id does not exist.
so...
//last id being the id of the last query set or updated
$last_id = $mysql->insert_id;
if($last_id != $id) {
//execute code
{
else {
echo "last id already in database!";
}
If I misinterpreted the question you should still be able to see how to use that last id to do what you want.
Here is an example of it being used. First we update the table with the form data which created our ID. Then we add the input check boxes array to the last id updated.
//define input variables
$lesson_id = $_POST['lesson_id'];
$user_id = $_POST['user_id'];
$instructor_id = $_POST['instructor_id'];
$lesson_comments = $_POST['lesson_comments'];
$lesson_date = date("Y-m-d");
$video_ids = isset($_POST['checkbox']) ? $_POST['checkbox'] : array(); # this is called a ternary operator
//insert lesson information first
$query ="INSERT INTO swing_viewer_lessons (lesson_id, user_id, instructor_id, lesson_comments, lesson_date) VALUES (?, ?, ?, ?, ?)";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("iiiss", $lesson_id, $user_id, $instructor_id, $lesson_comments, $lesson_date);
$stmt->execute();
//printf($stmt->error);
echo "successful";
//echo "$last_id";
}
//insert lesson information
if (is_array($video_ids) && count($video_ids) > 0)
{
foreach($video_ids as $list);
}
// Make it into a comma separated list
$rec_ids = implode(',', $video_ids);
//get last inserted id from above
$last_id= $mysqli->insert_id;
//finally query and update lesson information based on the last id added from above
$query ="UPDATE swing_viewer_lessons SET video_ids=? WHERE id=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("si", $rec_ids, $last_id);
$stmt->execute();
}
Hopefully this helps you or anyone else for that matter, as at one point I was pulling hair at this.
This question already has answers here:
if not exists insert in MySql
(2 answers)
Closed 9 years ago.
I'm a Java developer who just got handed the task of "some quick easy DB stuff" - except I don't know much about PHP/MySQL...I need to insert a record into a DB - but only if the email field doesn't match one that already exists in the DB. Here's what I've gleaned so far for my PHP code:
// Grab the values from the HTML form:
$newUserName = $_POST['newUserName'];
$newUserName = $mysqli->real_escape_string($newUserName);
$newUserEmail = $_POST['newUserEmail'];
$newUserEmail = $mysqli->real_escape_string($newUserEmail);
// Now search the DB to see if a record with this email already exists:
$mysqli->query("SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");
Now I need to see if anything came back from that search - meaning the email already exists - and if so I need to alert the user, otherwise I can go ahead and insert the new info into the DB using:
$mysqli->query("INSERT INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
Any ideas?
Working from your code, this should point you in the right direction. there are, perhaps, better ways to structure your database that will make better use of it.
<?php
$mysqli = new mysqli("localhost", "iodine", "iodine","iodine");
// Grab the values from the HTML form:
/*
$newUserName = $_POST['newUserName'];
$newUserName = $mysqli->real_escape_string($newUserName);
$newUserEmail = $_POST['newUserEmail'];
$newUserEmail = $mysqli->real_escape_string($newUserEmail);
*/
$newUserName = "Test User";
$newUserEmail = "test4#example.com";
// Now search the DB to see if a record with this email already exists:
echo "SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'", "\n";
$result = $mysqli->query("SELECT * FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");
if (!$result) {
die($mysqli->error);
}
echo "num_rows = ".$result->num_rows."\n";
if ($result->num_rows > 0) {
echo "Duplicate email\n";
// do something to alert user about non-unique email
} else {
$result = $mysqli->query("INSERT IGNORE INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
if ($result === false) {echo "SQL error:".$mysqli->error;}
}
?>
Consider putting a unique index on this particular table. The following code will add the index and remove any current duplicates:
ALTER IGNORE TABLE `RegisteredUsersTable` ADD UNIQUE INDEX unique_email (`UserEmail`);
Once this is added, use INSERT IGNORE or INSERT...ON DUPLICATE KEY UPDATE. They will only preform the insert if there is no duplicates.
$mysqli->query("INSERT IGNORE INTO RegisteredUsersTable (UserName, UserEmail) VALUES ('".$newUserName."', '".$newUserEmail."')");
Mysql will throw an error because the email is already in the database. However, the IGNORE command is telling the script to not pay any attention to errors for this query because, in this case, you expect it for a duplicate row.
Also, there is a way to alert your user with a failure or success message, even with INSERT IGNORE. Use MYSQL LAST_INSERT_ID(). If an ID was given, it was inserted. If not, then the email was already there (or there was another error).
As for your first query, to soften the load on servers, use count() instead.
$mysqli->query("SELECT count(*) FROM RegisteredUsersTable WHERE UserEmail = '$newUserEmail'");
This way, you can just check if you've gotten a result higher than 1. If the result is greater than 1, then the username exists (Since a row was returned).
To check the data returned, you need to simply execute the statement, then fetch the results. Part of the fun is learning, so here's the documentation
I am inserting a name, number, and company into a DB.
My table is simply:
id(primary key)
name
slideView
company
I need to update this information if a name passed to it exists, if not create a new row with this data. I have looked at REPLACE INTO but I dont think that will work for me... as I dont touch the ID at all.
My code is:
insertData($name,$count,$company);
function insertData($name, $count, $company) {
#Try/Catch statement to connect to DB, and insert data
try {
#DB username/password
$usernameDB = '****';
$passwordDB = '****';
#Create new PHP Database Object with the address, username, and password as parameters
$pdo = new PDO('mysql:host=localhost;dbname=*****', $usernameDB, $passwordDB);
#Set pdo attributes to handle errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#assign the sth variable (sth means statement handle) to insert the data
$sth = $pdo->prepare("REPLACE INTO ***** SET name = ?, slideView = ?, company = ?");
#Execute the insert
$sth->execute(array($name,$count,$company));
#Error if can't connect or insert
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}#/try
}
I'm new to SQL and havnt found a good way to do this yet.
You might be better of using the insert ... on duplicate update syntax for this, although it will mean passing a few extra params but it can quash certain problems in the replace into syntax that seem to keep cropping up.
REPLACE INTO ***** SET name = ?, slideView = ?, company = ?
Could be written as:
insert into yourTableName (name, slideView, company)
values (:name, :slideView, :company)
on duplicate key update set
slideView=:$slideView2, company=:company2
and then the execute is done like this:
$sth->execute(array(':name' => $name, ':slideView' => $count,
':company' => $company, ':slideView2' => $count, ':company2' => $company));
The format above uses named paramaters (they are ever so much easier to read/debug) and will insert a new row into the database - or if the unique/primary key column name already has the value, then update the row with the remainder of the information.
You do have to use paramaters twice here (even though slideView and company will contain the same information) as no parameter can be used twice in a query.
REPLACE INTO should work just fine - it also checks for columns with UNIQUE constraints. So you would just need to mark your name column as unique so that REPLACE INTO will identify it as duplicate.
I haven't tried this particular use case, but the documentation seems to allow it.