How to Select Database for an INSERT INTO statement - php

I have multiple SQL databases and I need to insert data into one of them. I am not sure how to select the database.
The following code was working when I only had 1 database, but now that there are multiple databases, this code no longer works.
$sql = "INSERT INTO users (username, first_name, last_name, email,
password, hash, avatar) "
. "VALUES
('$username','$first_name','$last_name','$email','$password', '$hash',
'$avatar')";
I want to write the above data into a table in a specific database.

You can set it while connection or just:
$sql = "INSERT INTO databasename.users (username, first_name, last_name, email, password, hash, avatar) "
. "VALUES ('$username','$first_name','$last_name','$email','$password', '$hash', '$avatar')";

Either of these might work
Use 'DBName.users' in the query instead of 'users'.
Execute the query 'use DBName;' before the insert query.

Related

Obtain UserID after inserting new record

I am currently working with a form where you are able to create new users. You would specify the username, firstname, etc and a new record would be inserted into the Users table in a database.
Right after the creation of an user more steps follow, but for these having the auto generated UserID in the session would be very useful.
How can I accomplish this? I tried the following:
sqlsrv_query($conn1,"INSERT INTO Users (Username, Firstname, Lastname, JobTitle)
VALUES ('$_POST[Username]', '$_POST[Firstname]', '$_POST[Lastname]', '$_POST[JobTitle]'); SELECT SCOPE_IDENTITY() AS UserID;");
$result = sqlsrv_query($conn1); $next_result = sqlsrv_next_result($result); $row = sqlsrv_fetch_array($result);
$_SESSION['UserID'] = $result;
Use OUTPUT INSERTED in your query.
Change Your Code Like,
$result = sqlsrv_query($conn1,"INSERT INTO Users
(Username, Firstname, Lastname, JobTitle) OUTPUT INSERTED.UserID
VALUES ('$_POST[Username]', '$_POST[Firstname]', '$_POST[Lastname]', '$_POST[JobTitle]');
and you will get last inserted id in $result

Return the ID of the last value inserted SQL

I'm inserting data into members table, after I've inserted it I want to get the userID of the information just inserted. Whats the best way about doing this ?
My php code
//Insert info into database
$sql = "INSERT INTO members (type, firstname, lastname, email, password, bio) VALUES ('$usertype', '$firstname', '$lastname', '$emailsighup', '$passwordsighnup', '$bio')";
//Run a query to check if data has been inserted correctly.
$records = mysqli_query($connect, $sql);
I did try this SQL but was getting errors
$sql = "INSERT INTO members (type, firstname, lastname, email, password, bio) VALUES ('$usertype', '$firstname', '$lastname', '$emailsighup', '$passwordsighnup', '$bio')"; SELECT SCOPE_IDENTITY(userID);
Assuming $connect as the variable holding your connection information, which seems legit, you can get the value of the last id with:
$user_id = mysqli_insert_id($connect);
This is something you can do from the PHP MySQLi interface, rather than directly from SQL!

I keep getting "Error Querying Database" in PHP code

Looks like I'm connecting to the server just fine. The problem seems to happen when it runs the query. It keeps saying
Error Querying Database
Here is my code:
<?php
$dbc = mysqli_connect('localhost', 'elvis_store')
or die('Error connecting to MySQL server.');
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email'];
$query = "INSERT INTO email_list (first_name, last_name, email)" .
"VALUES ('$first_name', '$last_name', '$email')";
mysqli_query($dbc, $query)
or die('Error querying database.');
echo 'Customer added.';
mysqli_close($dbc);
?>
You are getting this error because in your MySQLi connection you only give a location and username. You do not give a database name to be used. if you have no password, you need to write your connection like this:
$dbc = mysqli_connect('localhost', 'elvis_store', NULL, 'dbName)
or
$dbc = mysqli_connect('localhost', 'dbUsername', NULL, 'elvis_store')
if "elvis_store" is the database name and not the username. Remember, a mysqli connection is: mysqli_connect(dbLocation, dbUsername, dbPassword, dbName).
Also, as Ed has pointed out in another answer, there is also a syntax error in your MySQL statement. Here is the snippet from Ed's answer:
$query = "INSERT INTO email_list (first_name, last_name, email) " . "VALUES ('$first_name', '$last_name', '$email')";
You have multiple problems.
Problem 1: Syntax error
Your query has a typo (a missing space). Your query code
$query = "INSERT INTO email_list (first_name, last_name, email)" .
"VALUES ('$first_name', '$last_name', '$email')";
produces this query:
INSERT INTO email_list (first_name, last_name, email)VALUES ('$first_name', '$last_name', '$email')
-- ^ syntax error, missing space
To fix it, change your code to this:
$query = "INSERT INTO email_list (first_name, last_name, email) " .
"VALUES ('$first_name', '$last_name', '$email')";
At least for testing purposes, you probably should look at the output of mysqli_error() instead of using a generic message like Error querying database. Even in production, you'll want to trap and log the real error somehow.
Problem 2: You don't select a database
Edit: I missed this in my first glance at your question, but as Stephen Cioffi points out, you also need to select a database before running your query. You can do this with the schema parameter to mysqli_connect() or by using mysqli_db_select().
Both of these issues—the typo and the failure to select a database—will cause problems; you must fix both.
Problem 3: Huge SQL Injection Vulnerability
This is not strictly part of the answer, but it's important. You are wide open to SQL injection. You need to use prepared statements. Otherwise, you are going to get hacked. Imagine that the POSTed firstname is this:
', (SELECT CONCAT(username, ',', password) FROM users WHERE is_admin = 1), 'eviluser#example.com') --
Your query becomes (with some added formatting):
INSERT INTO email_list (first_name, last_name, email)
VALUES ('',
(SELECT CONCAT(username, ',', password) FROM users WHERE is_admin = 1),
'eviluser#example.com'
) -- ', 'value of lastname', 'value of email')
Then, when you email your users, somebody's going to get an email with a recipient like
"Duke,mySup3rP#ssw0rd!" <eviluser#example.com>
And... you're hosed.
(Hopefully, you're salting and hashing passwords, but still, this is disastrous.) You must use prepared statements.

Having trouble using MySQLi INSERT queries

Okay, so I'm updating my site from MySQL to MySQLi, which means I have to re-code some of the database stuff.
I looked on php.net on how to use MySQLi queries to insert data into a table and did exactly what they said to, but no luck.
Here's my connection variable:
$con = mysqli_connect("localhost", "username", "password", "database");
And here is the code to insert the data:
mysqli_query($con, "INSERT INTO users ('user', 'pass', 'email') VALUES ('$user', '$pass', '$email')");
It doesn't reply with any errors, and it just takes me to the intended landing page. It doesn't actually add the data to the table though.
Any ideas?
As answered above, removing the quotes from the column names will solve your problem:
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('$user', '$pass', '$email')");
But I also noted that your script is vulnerable against SQL injection attacks.
In MySQLi you can prepare your statements before execution, so you will be sure that no one will inject SQL commands in your database.
If you don't want to prepare each sql statements before execution, at least use the mysqli_real_escape_string function, that will protect your system against SQL injection too. Use like that:
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('" . mysqli_real_escape_string($user) . "', '" . mysqli_real_escape_string($pass) . "', '" . mysqli_real_escape_string($email) . "')");
remove single quotes from column names
mysqli_query($con, "INSERT INTO users (user, pass, email) VALUES ('$user', '$pass', '$email')");
OR
mysqli_query($con, "INSERT INTO users (`user`, `pass`, `email`) VALUES ('$user', '$pass', '$email')");

Inserting Integer value into mysql int using INSERT

I'm trying to insert a new record in a MySQL database from PHP, which I've done a million times before, but for some reason, I can't get it to work this time, and it really bugs me.
Inserting strings into all the varchar collumns are going great, but when I get to inserting a value into the int column, I get an error telling me that I have a syntax error.
Basically, the first query works just fine, but the second one returns the error, and as you can see, I've made damn sure it really is an integer I'm trying to insert.
I hope somebody can help. I'm really starting to develop a headache over this :/
$groupId2 = 5;
$groupId = (int)$groupId2;
if(!mysqli_query($link, "INSERT INTO contestants (firstName, lastname, email) VALUES ('$firstName', '$lastName', '$email')"))
echo "First: " . mysqli_error($link);
if(!mysqli_query($link, "INSERT INTO contestants (firstName, lastname, email, group) VALUES ('$firstName', '$lastName', '$email', '$groupId')"))
echo "Second: " . mysqli_error($link);
group is a mysql keyword use back quotes around it
"INSERT INTO contestants (firstName, lastname, email, `group`)
VALUES ('$firstName', '$lastName', '$email', '$groupId')"
The error is because you surrounded your int with ' ', you need to get rid of your apostrophes and it will work just fine.
if(!mysqli_query($link,
"INSERT INTO contestants
(firstName, lastname, email, group) VALUES
('$firstName', '$lastName', '$email', $groupId)"))
^^^^^^^^^
To clarify, when inserting numerical fields you do not need them.
According to pst this is wrong, although, the fact you do not need single quotes is still correct.

Categories