ok so I can connect and view the database with my php code, however I can not insert data into it.here is the query I tested with phpmyadmin which was able insert new data into my table
INSERT INTO `members` ( `id` , `username` , `email` )
VALUES ( 123456789, 'russi', 'baka#dog.com' )
then I tried to put it into my actual php file
<?php
$servername = "localhost";
$username = "root";
$password = "blablabla";
$dbname = "test_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - username: " . $row["username"]. " -email:" . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
so select function works but insert does not.
You are overriding your $sql variable w/o executing it. Besides that you should not use single quotes for columns, but backticks (see When to use single quotes, double quotes, and backticks in MySQL)
Change
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
to
$sql = "INSERT INTO `members` (`id`, `username`, `email`)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$result = $conn->query($sql);
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
Change your insert to:
$sql = "INSERT INTO members (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
And call your query:
$sql = "INSERT INTO members (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
//Here, you never execute your query
$result = $conn->query($sql);
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
Of course it did not work !
You never execute your INSERT...
<?php
...
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$conn->exec($sql);
$sql = "SELECT id, username, email FROM members";
$result = $conn->query($sql);
...
:)
remove the single quotes around your column and table names:
$sql = "INSERT INTO members (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
single quotes are only used for char fields.
Also you never execute the insert Statement because you overwrite it.
$sql = "INSERT INTO 'members' ('id', 'username', 'email')
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT id, username, email FROM members";
//missing the grave accent
$sql = "INSERT INTO `members` (id, username, email)
VALUES (2339978, 'vladtheimpalor', 'vladtheimaplor#bloody.com')";
$sql = "SELECT `id`, `username`, `email` FROM `members`";
/* This is the corrrected code */
Related
$sql3 = "INSERT INTO users_addresses (ua_user_id,ua_address_id) VALUES ('','')";
I am new in php and my hint is to link 2 tables id's in in another one called users_addresses.When a user is registered in my database i want the user_id and address_id to clone in users_addresses(ua_user_id,ua_address_id)
My tables
$sql = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}', '{$_SESSION['userinfo']['mname']}', '{$_SESSION['userinfo']['lname']}', '{$_SESSION['userinfo']['login']}', '{$_SESSION['userinfo']['email']}', '{$_SESSION['userinfo']['phone']}')";
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
$sql2 = "INSERT INTO notes (note_text)
VALUES ('{$_SESSION['noteinfo']['note']}')";
These are my others SQL codes for adding session's data in DB.
Just need get user_id from first sql. If you are using mysqli function, do this
// run your first sql: insert user
mysqli_query($con, $sql);
$user_id = mysqli_insert_id($con); // or mysqli::$insert_id
Next, you have $user_id variable with user id.
$sql1 = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ($'{$_SESSION['addressinfo']['adr1']}', '{$_SESSION['addressinfo']['adr2']}', '{$_SESSION['addressinfo']['zip']}', '{$_SESSION['addressinfo']['city']}', '{$_SESSION['addressinfo']['provinciq']}', '{$_SESSION['addressinfo']['durjava']}')";
mysqli_query($con, $sql);
$address_id = mysqli_insert_id($con); // or mysqli::$insert_id
$sql3 = "INSERT INTO users_addresses (ua_user_id, ua_address_id) VALUES ($user_id, $address_id)";
mysqli_query($con, $sql);
Use mysqli_insert_id() to get the unique ID of the insert table, this example uses Procedural style:
<?php
include 'connection.php';
......
$InsertSQL = "INSERT INTO users (user_fname,user_mname,user_lname,user_login,user_email,user_phone)
VALUES ('{$_SESSION['userinfo']['fname']}',
'{$_SESSION['userinfo']['mname']}',
'{$_SESSION['userinfo']['lname']}',
'{$_SESSION['userinfo']['login']}',
'{$_SESSION['userinfo']['email']}',
'{$_SESSION['userinfo']['phone']}')";
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
$UserID = mysqli_insert_id($conn); // <-- get the UserID
$InsertSQL = "INSERT INTO addresses (address_line_1,address_line_2,address_zip,address_city,address_province,address_country)
VALUES ('{$_SESSION['addressinfo']['adr1']}',
'{$_SESSION['addressinfo']['adr2']}',
'{$_SESSION['addressinfo']['zip']}',
'{$_SESSION['addressinfo']['city']}',
'{$_SESSION['addressinfo']['provinciq']}',
'{$_SESSION['addressinfo']['durjava']}')";
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
$AddressID = mysqli_insert_id($conn); // <-- get the AddressID
$InsertSQL = "INSERT INTO user_addresses (ua_user_id,ua_address_id)
VALUES ($UserID,$AddressID)"; // <-- INSERT INTO user_address
$ResultSQL = mysqli_query($conn, $InsertSQL) or die(mysqli_error($conn)); // <-- execute your query
?>
You should also look into SQL Injection vulnerability, check out prepared statements.
Hope that helps.
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
I am trying to convert my mysqli database that was very vulnerable to PDO prepared statements. I think i almost got it since it actully inputs the registration data to the database but not to the other databases. So i think there must be some issues on those queries but i can't figure it out. Here below is my code.
<?php
session_start();
// DATABASE CONNECTION
$user = '****';
$pass = '****';
//CREATE CONNECTION
// $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$pdo = new PDO('mysql:host=localhost;dbname=****', $user, $pass);
// ASSIGN VARIABLE FROM FORM
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$password = password_hash($password, PASSWORD_BCRYPT);
// CHECK IF USER IS UNIQUE
$stmt = $pdo->prepare("SELECT username FROM users WHERE username = :name");
$stmt->bindParam(':name', $username);
$stmt->execute();
if ($stmt->rowCount() > 0) {
echo "That username already exist!";
} else {
//INSERT DATA INTO DATABASE
$sql = "INSERT INTO users ( username, password, email )
VALUES ( :username, :password, :email )";
$sql1 = "INSERT INTO stats (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
$sql2 = "INSERT INTO progression (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
$sql3 = "INSERT INTO powervalues (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
// EXECUTE AND PREPARE
$query = $pdo->prepare($sql);
$query1 = $pdo->prepare($sql1);
$query2 = $pdo->prepare($sql2);
$query3 = $pdo->prepare($sql3);
$result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
$result1 = $query1->execute(array( ':username'=>$username ));
$result2 = $query2->execute(array( ':username'=>$username ));
$result3 = $query3->execute(array( ':username'=>$username ));
//EXECUTE QUERY
if ($result && $result1 && $result2 && $result3) {
$_SESSION['Accountsucess'] = "Account has been added sucessfully.";
header("location: ../../index.php?page=index");
} else {
echo "Error database failure";
}
}
Instead of continually selecting various parts of information, once you have inserted the user in the users table, fetch the last insert ID and then use that in subsequent calls...
$sql = "INSERT INTO users ( username, password, email )
VALUES ( :username, :password, :email )";
$sql1 = "INSERT INTO stats (id, username)
VALUES (:id,:username)";
// EXECUTE AND PREPARE
$query = $pdo->prepare($sql);
$query1 = $pdo->prepare($sql1);
$result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
// Fetch id of new user
$id = $pdo->lastInsertId();
$result1 = $query1->execute(array( ':id' => $id, ':username'=>$username ));
Repeat this same logic for each of the other statements.
$name = mysqli_real_escape_string($connection, $_POST["name"]);
$surname = mysqli_real_escape_string($connection, $_POST["surname"]);
$username = mysqli_real_escape_string($connection, $_POST["username"]);
$email = mysqli_real_escape_string($connection, $_POST["email"]);
$pw1 = mysqli_real_escape_string($connection, $_POST["pw1"]);
$query = "INSERT INTO 'users' ('id','name', 'surname', 'username', 'email', 'password') VALUES (NULL,'$name', '$surname', '$username', '$email', '$pw1')";
$result = mysqli_query($connection, $query);
if(!$result){
echo ("fail");
}
I test if the query has worked using if(!$result){ echo ("fail");} and it echoes fail every time and no data is inserted into the database every time! I have checked the syntax and i believe it is correct... could this be because of the database "collation"?
You should not use the single quote at the table or field name. You have to use a Backtick (like ``) which is located in under Esc key or left side of 1 Key or upper side of Tab key. It should looks like:
$query = "INSERT INTO `users` (`id`, `name`, `surname`, `username`, `email`,
`password`) VALUES ('null', '$name', '$surname', '$username', '$email', '$pw1')";
or
$query = "INSERT INTO users (id, name, surname, username, email,
password) VALUES ('null', '$name', '$surname', '$username', '$email', '$pw1')";
Note: If your id field is already set auto increment then you can remove id and value null. Because id value will automatically increment.
Hope it will helpful.
I have created a php function that allows users to save their address on the database. My issue is that part of the code doesn't run at all. The code stops running at $result2= "SELECT * FROM Addressv4 WHERE Userid = '".$id."'";
It then starts working when it reaches this line of code $insert_query = "INSERT INTO Addressv4 (Userid, Housenumber, Street, Town, Postcode, DefaultAddress)
values ('$id', '$Number', '$Street', '$Town','$Postcode', '1')";
I haven't received any syntax errors when running the code either.
Any help would be grateful.
<?php
include 'dbconnect.php';
$connection = mysqli_connect($db_host, $db_username, $db_password, $db_database);
// Check connection
if (mysqli_connect_errno($connection)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Getting data from HTML Form
$Number = $_POST['streetnumber'];
$Street = $_POST['street'];
$Town = $_POST['town'];
$Postcode = $_POST['postcode'];
$Username = $_POST['Username'];
$sql = mysqli_query($connection, "SELECT * FROM Userv2 WHERE Username = '".$Username."'");
if ($sql){
while($row = mysqli_fetch_array($sql)){
$id = $row['Id'];
}
}
$result2= "SELECT * FROM Addressv4 WHERE Userid = '".$id."'";
$sql1 = mysqli_query($connection, $result2);
$count = count($sql1);
if($count >=1){
echo 'Sorry you can only have 1 default address';
}
$insert_query = "INSERT INTO Addressv4 (Userid, Housenumber, Street, Town, Postcode, DefaultAddress)
values ('$id', '$Number', '$Street', '$Town','$Postcode', '1')";
$result = mysqli_query($connection, $insert_query);
header("Location: http://sots.brookes.ac.uk/~10031187/viewaddress.php");
mysqli_close($connection);
?>
maybe it's better to use
SELECT COUNT(Userid) AS countId FROM..
if ($row['countId'] > 1) {
that way the query will always return something, now there is a chance your query can return false..
what is the output of var_dump($sql1); ?
$sql1 is a resulset. You cannot count the number of lines like this.
Try :
$sql1_count = mysqli_num_rows($sql1)
Right now, this is what I have:
$query = "INSERT INTO COMMENTS VALUES ('$user', '$comment', '$star')";
mssql_query($query, $connection);
$commentIDQuery = "SELECT SCOPE_IDENTITY() AS ins_id";
$CI = mssql_query ($commentIDQuery, $connection);
$commentID = mssql_fetch_row($CI);
$idQuery = "SELECT recipeid FROM t_recipe WHERE recipename = '$recipeName'";
$RID = mssql_query($idQuery, $connection);
$recipeID = mssql_fetch_row($RID);
$rcQuery = "INSERT INTO COMMENT_RECIPE VALUES ('$commentID[0]', '$recipeID[0]')";
mssql_query($rcQuery, $connection);
So how would I get that ins_id?
It adds it to the first table, which is comments, but not the relation table.
Using sql server 2008
What about this......
$query = "DECLARE #NewID INT
INSERT INTO COMMENTS VALUES ('$user', '$comment', '$star');
SELECT #NewID = SCOPE_IDENTITY();
INSERT INTO COMMENTS_RECIPE VALUES (#NewID, '$recipeid')";
$stmt = sqlsrv_query($conn,$query);