INSERT Multiple Database Values To Specific Rows - php

How can I INSERT the values of this function to only WHERE the value of the username column (located in the login table, contains the exact same value as the value of the column nickname (located in a table called active_users).
$stmt = $this->pdo->prepare('INSERT INTO login (device_token) VALUES (?)');
$stmt->execute(array($token));
Additional info: when a user logs in, I set up the API to add the user's name to both username (in the login table) and nickname in the active_users table. Since these values will always be the same for their respective tables, I was hoping we could add some conditional logic to achieve this type of specificity. My goal is to take the device_token parameter and pass it to a different spot in the database.
Edit: Schema
Update AFNetworking command for login
NSMutableDictionary* params =[NSMutableDictionary dictionaryWithObjectsAndKeys:command, #"command", _nicknameTextField.text = fldUsername.text, #"username", hashedPassword, #"password", nil ];
Update: active_users INSERT statment
$stmt = $this->pdo->prepare('INSERT INTO active_users (user_Id, device_token, nickname, secret_code, ip_address) VALUES (?, ?, ?, ?, ?)');
$stmt->execute(array($userId, $token, $name, $code, $_SERVER['REMOTE_ADDR']));

If I understand you correctly. What you really want is an update and not an insert.
You want to add the value of device_token to the row with nickname, correct?
You would do that with an update:
UPDATE login
SET device_token = #token
WHERE username = #nickname
If you're trying to update the record with an existing record from active_users table than:
UPDATE login AS L
JOIN active_users AU ON L.username = AU.nickname
SET L.device_token = AU.device_token
Though, looking at your tables. I'm wondering if you're repeating too much of the data. It seems like you can link login and active_users by user_id. Well, this would get off topic, so I'll just suggest double checking db design concepts and your needs.

Using PDO it should be
UPDATE login
SET device_token = :token
WHERE username = :nickname
where the params array that will be bound looks like
$params = array("token" => $token, "nickname" => $nickname);
Full example:
$stmt = $this->pdo->prepare('UPDATE login SET device_token=:token WHERE nickname=:nickname');
$stmt->execute(array("token" => $token, "nickname" => $nickname));
Or you use the method of binding with ?
UPDATE login
SET device_token = ?
WHERE username = ?
where the parameter array is
$params = array($token, $nickname);
Full example:
$stmt = $this->pdo->prepare('UPDATE login SET device_token=? WHERE nickname=?');
$stmt->execute(array($token, $nickname));

Related

Bind textfield value to array and put in database

I'm making a simple private messing system. When a user sends a message he/she has to fill in three fields: 'to', 'subject' and 'message'. In the 'to' field a user can enter a username to send his/hers message to. Then, using mySql (phpmyadmin), I try to fetch the corresponding user_id from the users table.
for example, user_id '1' has user_name 'testing'. When a user types in 'testing' in the 'to' field, my code searches in the users table for the user with the user_name 'testing' and takes the corresponding user_id.
After taking the user_id it puts the user_id in the conversations_members table.
My problem is that the code DOES take the correct user_id (I checked this by printing the array), but it doesn't put the correct user_id in the table. It always puts 0.
See code below, here I add the user_id to the array $user_ids
else if(!empty($_POST['to'])){
$stmt = $db->prepare("SELECT user_id FROM user WHERE user_name = :user_name");
$stmt->bindValue(':user_name', $_POST['to'], PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result) {
$user_ids['user_id'] = $result['user_id'];
}
See code below, here I try to add the user_id to the table
$sql4 = $db->prepare("INSERT INTO conversations_members
(conversation_id, user_id, conversation_last_view, conversation_deleted)
VALUES (:conid, :usid, :clv, :condel)");
$sql4->execute(array(
"conid" => "{$conversation_id}",
"usid" => "{$user_ids[0]['user_id']}",
"clv" => "0",
"condel" => "0"
));
I really hope anyone can help, I've been struggling for a few hours now :(
Thanks in advance!!

Find and Post in table using php

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.

PDO insert new record to database based on lastInsertId()

Ive just started learning PDO and I'm struggling by simply inserting a new record based from
$lastid = $db->lastInsertId();
The ID gets created in the database table from another function.
But nothing happens when i try to insert a new record based on that ID.
function add_name($last_id, $name) {
$db = some_db();
$query = "INSERT INTO team (name) VALUES (:name) WHERE id = '".$last_id."'";
$stmt = $db->prepare($query);
$stmt ->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
}
INSERT ... WHERE is not valid SQL. If you are inserting a new record, an autoincremnt ID will be generated at that time (if you have such defined for the table).
If you are trying to INSERT a new row into a related table with the last id from another table, then you would set that value as one of your column inputs. So the workflow would look like this:
INSERT [column data for table_a] INTO table_a
[GET autoincrement from last insert]
INSERT (table_a_foreign_key_column, [other table_b columns]) VALUES (table_a_id, [other table_b values) INTO table_b
UPDATE:
Since UPDATE is what you want, you can make update like this:
UPDATE team
SET name = :name
WHERE id = :id
You should use parameters for both name and id values. It is still not clear to me why you would need to make an insert and then an update within the same script execution. It's not like you received any more input from the user that you did not already have. I would guess you could just insert this name values when first creating the record and save yourself the extra trouble of multiple queries.
i think your sql query is wrong, try this:
function add_name($last_id, $name) {
$db = some_db();
$query = 'INSERT INTO team (id, name) VALUES (:id, :name)';
$stmt = $db->prepare($query);
$stmt ->bindParam(':name', $name, PDO::PARAM_STR);
$stmt ->bindParam(':id', $last_id, PDO::PARAM_INT);
$stmt->execute();
}
MySQL Insert Where query

Concatenating a string and primary key Id while inserting

I have a user table in mysql, I insert data like this:
/* prepare query */
$query = 'INSERT INTO `users`(`first_name`,
`last_name`,
`gender`,
`username`,
`profile_picture`,
`provider`,
`provider_id`,
`provider_username`,
`provider_profile`,
`provider_profile_picture`,
`last_login`,
`created_date`,
`ip_address`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), INET_ATON(?))';
/* Prepare an insert statement */
$stmt = $mysqli->prepare($query);
if($stmt){
$stmt->bind_param("sssssssssss", $user['first_name'],
$user['last_name'],
$user['gender'],
$user['username'],
$user['profile_picture'],
$user['provider'],
$user['id'],
$user['username'],
$user['link'],
$user['profile_picture'],
$_SERVER['REMOTE_ADDR']);
$stmt->execute();
/* Execute the statement */
I would like to make the username be equal to 'user' + userId which is autoincremental primary key field.
so that the usernames get in order:
user1
user2
user3 and so forth
what is a slick way to accomplish that?
If user_id is an AUTO_INCREMENT primary key, then you can't do this with a single statement, even if you use a trigger.
The problem is that the AUTO_INCREMENT value isn't generated until after the BEFORE INSERT trigger runs, but you can't change username in the AFTER INSERT trigger.
So you just have to do the INSERT, then immediately do an UPDATE.
If user_id is not an AUTO_INCREMENT, but instead is something you specify yourself, then it's easy, you just do the concatenation in your PHP code before you pass the values as parameters.
Update: You can't do it with MySQL 5.7 generated columns either. It results in this error when you try to create the table:
Generated column 'username' cannot refer to auto-increment column.
Assuming the username is always 'user' + userid, the slickest way I can think of to do this is to have a table with everything except username in it, and a view on top of that table that adds username. You would then do any inserts and updates on the table, and any selects that require username could be done on the view.
CREATE VIEW userview AS
SELECT user_id, first_name, last_name, gender, profile_picture, provider,
provider_id, provider_username, provider_profile, provider_profile_picture,
last_login, created_date, ip_address, 'user' + user_id as username
FROM USER

Using LastInsertId Multiple times, PHP PDO

I have this registration stuff, and I want to 3 tables to be filled with data as soon as the user clicks add user
the tables were:
users
roles
status
user_role
user_status
The system must insert the data as follows
users table:
username
password
user_roles
user_id
default value
user_status
user_id
default value
i used pdo begin transaction stuff and commit stuff to make this work...
this worked great when I used it on just two tables, however when i decide to use another table and do the same code pattern, it did not work at all.
here are the codes:
$this->db->beginTransaction();
$sth = $this->db->prepare("INSERT INTO users (username, password)
VALUES (:user,:pass)");
$sth->execute(array(
':user'=> $data['user'],
':pass'=> Hash::create('sha256', $data['pass'], HASH)
));
$sth = $this->db->prepare("INSERT INTO user_role (user_id, role_id) VALUES (:user, :role)");
$sth->execute(array(
':user' => $this->db->lastInsertId(),
':role' => 3
));
$sth = $this->db->prepare("INSERT INTO user_status (user_id, status_id) VALUES (:user, :status)");
$sth->execute(array(
':user' => $this->db->lastInsertId(),
':status' => 1
));
$this->db->commit();
What do you think is the problem, I also doubt this is some kind of a syntax error, but I could not find, it, so my last resort is to ask, for I am not sure also if this works on 3 tables. Thank you!
after your first insert:
$insertID = $this->db->lastInsertId();
then in the following INSERTS
':user' => $insertID,

Categories