php- data not entered to database - php

I am trying to enter 3 different data to a mysql database 'pages'
The first 2 data is submitted to the database but the third 'dname' is not.
The $_SESSION['dname'] contains the value to be added to the column 'dname'
The php looks like:
if (isset($_POST['submit']))
{
$menulabel = $_POST['menulabel'];
$content = $_POST['content'];
$dname = $_SESSION['dname'];
$query = "INSERT INTO pages (menulabel, content, dname) VALUES (?, ?, ?)";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('sss', $menulabel, $content, $dname);
$statement->execute();
$statement->store_result();
if ($statement->error)
{
die('Database query failed: ' . $statement->error);
}
$creationWasSuccessful = $statement->affected_rows == 1 ? true : false;
if ($creationWasSuccessful)
{
header ("Location: index.php");
}
else
{
echo 'Failed';
}
}
The mysql table:
$query_pages = "CREATE TABLE IF NOT EXISTS pages (id INT NOT NULL AUTO_INCREMENT, menulabel VARCHAR(50), content TEXT, dname VARCHAR(50), PRIMARY KEY (id))";
$databaseConnection->query($query_pages);
The php successfully adds the 'menulabel' and 'content' to the table and continues leaving the 'dname' NULL.
Please help, this is my first time with php.

Here you go buddy. This should fix your issue. Instead of throwing the object into the params, utilize it in the query instead.
$menulabel = $_POST['menulabel'];
$content = $_POST['content'];
$dname = $_SESSION['dname'];
$query = "INSERT INTO pages (menulabel, content, dname) VALUES (?, ?, '$dname')";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('ss', $menulabel, $content);
$statement->execute();
$statement->store_result();

Related

How to insert data into table with foreign key using html form and php?

Situation: user is logged in and wants to save their favorite color through html form. But in phpMyAdmin I can see that the foreign key and the primary key (which are columns 'user_id' in two separate tables) do not match. The foreign key shows NULL in the rows with data, while the primary key shows numbers (e.g. 3) in the rows with data.
As mentioned, there are 2 tables: (users & colors)
The following sql is used to create table colors:
CREATE TABLE colors (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
favorite_color TEXT NOT NULL,
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
The following sql is used to create table users:
CREATE TABLE users (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
From the page where users insert data is welcome.php and it contains the following code:
<?php
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login");
exit;
}
?>
The html form:
<form action="welcome.php" method="post">
<label>My favorite color:
<input type="text" name="favorite_color">
</label>
<input type="submit" value="Save">
</form>
And the php code to insert data:
<?php
$link = mysqli_connect("localhost", "root", "", "my_db");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO colors (id, favorite_color, user_id) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "sss", $id, $favorite_color, $user_id);
$id = $_REQUEST['id'];
$favorite_color = $_REQUEST['favorite_color'];
$user_id = $_REQUEST['user_id'];
if(mysqli_stmt_execute($stmt)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
}
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>
What am I doing wrong? Any suggestion is welcome. Thanks.
I have been able to solve the problem.
Here's what I did:
I changed:
$sql = "INSERT INTO colors (id, favorite_color, user_id) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "sss", $id, $favorite_color, $user_id);
into:
$sql = "INSERT INTO colors (favorite_color, user_id) VALUES (?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "si", $favorite_color, $user_id);
As you can see I removed 'id' and changed "sss" into "si".
And I changed:
$id = $_REQUEST['id'];
$favorite_color = $_REQUEST['favorite_color'];
$user_id = $_REQUEST['user_id'];
into:
$favorite_color = $_REQUEST['favorite_color'];
$user_id = $_SESSION['user_id'];
I removed 'id' entirely and I replaced REQUEST with SESSION for the column 'user_id'.
It is now showing matching numbers under 'user_id' in table colors.

MySql: Insert values in an auto_increment field with PHP

What I'm actually trying to do is insert a row with:
INSERT INTO users VALUES (col1, col2, ...)
where col1 is an auto_increment.
The PHP code is:
<?php
$host = "http://name.altervista.org/";
$user = "name";
$psw = "";
$db = "my_name";
$response = array();
$response["success"] = true;
$connessione = new mysqli($host, $user, $psw, $db);
if($connessione->connect_errno == 0)
{
$nome = $_POST["nome"];
$cognome = $_POST["cognome"];
$username = $_POST["username"];
$password = $_POST["password"];
$nTelefono = $_POST["nTelefono"];
$email = $_POST["email"];
$sql = "INSERT INTO users
VALUES (DEFAULT, '$nome', '$cognome', '$username', '$password', '$nTelefono', '$email')";
$ris = $connessione->query($sql);
if($connessione->affected_rows == 1)
{
echo(json_encode($response));
}
else
{
$response["success"] = false;
echo(json_encode($response));
}
}
else
{
$response["success"] = false;
echo(json_encode($response));
}
?>
I search similar questions here in stackoverflow, and I try to use DEFAULT or NULL, but it doesn't work. And if I put a number instead of the default value that is not already in the table it works, so I really don't understand where the problem is.
Have you any other suggestions?
EDIT: The table structure on the database:
click
EDIT 2: I tried to delete the table and create it again, and now it works with the NULL thing. Thanks for the support!
When you are doing an insert, list all the columns being inserted. You seem to want:
INSERT INTO users (nome, cognome, username, password, nTelefono, email)
VALUES ('$nome', '$cognome', '$username', '$password', '$nTelefono', '$email');
Next. Never store clear-text passwords in the database. You should be encrypting the value on the client side so the values are never passed over the network.
Next. Learn to use parameterized queries. When you munge query strings with parameter values, your are asking for inexplicable syntax errors and making the code subject to SQL injection attacks.
From the Mysql docs
INSERT INTO users VALUES ('$nome', '$cognome', '$username', '$password', '$nTelefono', '$email')";
The auto_increment fields doesn't need to be set in an INSERT statement
In MySQL, if you have an auto_increment column you don't need to put it in the insert statement.
Example:
You have the table:
CREATE TABLE test (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL
);
Your SQL statement should be:
INSERT INTO test(name) VALUES ('My name');

PHP Prepared statements inserting data into all but one table (MySQL)

I'm working on an inbox system. On the front end, it uses jQuery and Ajax so the page doesn't refresh. I've got that part handled. On the back end, there are 3 tables (for now) that get data inserted.
Here is a basic rundown of the relation structures:
conversations:
conversation_id int(11) primary key
conversation_subject varchar(128)
conversations_members:
conversation_id int(11)
user_id int(11)
conversation_last_view int(10)
conversation_deleted int(1)
conversations_messages:
message_id int(11) primary key
conversation_id int(11)
user_id int(11)
message_date timestamp
message_text text
There is an additional problem since the sender_id is always 0, but that will have to be for another question since it's off topic.
The problem lies in the conversations_members table. Everything else gets entered into the conversations and conversations_messages tables. Here is the PHP. The issue is the very last SQL query at the bottom:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include('../inc/connect.php');
if (!isset($_SESSION['username'])) {
session_start();
}
$recipient_username = "";
$sender_id = "";
$a = 0;
$b = 0;
if(isset($_POST['subject'], $_POST['msg_body']) && !empty($_POST['subject']) && !empty($_POST['msg_body'])) {
//get ID of sender
$sender_id_query = "SELECT id FROM `users` WHERE username = ?";
$stmt = $connection->prepare($sender_id_query);
$stmt->bind_param('s', $_SESSION['username']);
$stmt->execute();
$result = mysqli_query($connection, $sender_id_query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
//$row['id'] = $sender_id; //neither of these work
$sender_id = $connection->insert_id; //Always zero
}
}
$stmt->close();
//get username of recipient
$recipient_name_query = "SELECT * FROM `users`";
$result = mysqli_query($connection, $recipient_name_query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$row['username'] = $recipient_username;
}
}
//define post variables
$msg_subject = $_POST['subject'];
$msg_body = $_POST['msg_body'];
$subject = $connection->real_escape_string(htmlentities($msg_subject));
$body = $connection->real_escape_string(htmlentities($msg_body));
$conversation_id = mysqli_insert_id($connection);
//GET RECIPIENT ID
$sql = "SELECT id FROM `users` WHERE username=?";
$stmt = $connection->prepare($sql);
$stmt->bind_param('s', $recipient_username);
$result = mysqli_query($connection, $sql);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$recipient_id = $row['id'];
}
}
$stmt->close();
//INSERT SUBJECT INTO CONVERSATIONS TABLE
$stmt = $connection->prepare("INSERT INTO `conversations` (conversation_subject) VALUES(?)");
$stmt->bind_param('s', $subject);
$stmt->execute();
$stmt->close();
//INSERT THE IDs AND TIMESTAMPS INTO MESSAGES TABLE
$stmt = $connection->prepare("INSERT INTO `conversations_messages` (conversation_id, user_id, message_date, message_text)
VALUES(?, ?, NOW(), ?)");
$stmt->bind_param('iis', $conversation_id, $sender_id, $body);
$stmt->execute();
$stmt->close();
/*
THE FOLLOWING DATA DOES NOT GET INSERTED.....
*/
//INSERT IDs, LAST_VIEWED, AND DELETED INTO MEMBERS TABLE
$stmt = $connection->prepare("INSERT INTO `conversations_members` (conversation_id, user_id, conversation_last_view, conversation_deleted)
VALUES (?, ?, ?, ?)");
$stmt->bind_param('iiii', $conversation_id, $recipient_id, $a, $b);
$stmt->execute();
$stmt->close();
}
I get no errors, and I'm not seeing any typos. Where did I go wrong?
Thanks to the suggestion of additional error checking, it led me to discover what was happening. I completely removed the while loops, and gave each $stmt variable it's own name since I discovered another error after removing the while loops. Every statement after the first was returning a FALSE value since the previous statement wasn't closed. This code works. I get no errors, and it inserts everything into the database as required.
$recipient_username = $_GET['username'];
$username = $_SESSION['username'];
$a = 0;
$b = 0;
//get ID of sender
$sender_id_query = "SELECT id FROM `users` WHERE username = ?";
$stmt = $connection->prepare($sender_id_query);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($sender_id);
$val = $stmt->fetch()[$sender_id];
$stmt->close();
//define post variables
$msg_subject = $_POST['subject'];
$msg_body = $_POST['msg_body'];
$subject = $connection->real_escape_string(htmlentities($msg_subject));
$body = $connection->real_escape_string(htmlentities($msg_body));
$conversation_id = mysqli_insert_id($connection);
//GET RECIPIENT ID
$recipient_id_query = "SELECT id FROM `users` WHERE username=?";
$stmt2 = $connection->prepare($recipient_id_query);
$stmt2->bind_param('s', $recipient_username);
$stmt2->execute();
$stmt2->bind_result($recipient_id);
$val_2 = $stmt2->fetch()[$recipient_id];
$stmt2->close();
//INSERT SUBJECT INTO CONVERSATIONS TABLE
$stmt3 = $connection->prepare("INSERT INTO `conversations` (conversation_subject) VALUES(?)");
$stmt3->bind_param('s', $subject);
$stmt3->execute();
$stmt3->close();
//INSERT THE IDs AND TIMESTAMPS INTO MESSAGES TABLE
$stmt4 = $connection->prepare("INSERT INTO `conversations_messages` (conversation_id, user_id, message_date, message_text)
VALUES(?, ?, NOW(), ?)");
$stmt4->bind_param('iis', $conversation_id, $sender_id, $body);
$stmt4->execute();
$stmt4->close();
//INSERT IDs, LAST_VIEWED, AND DELETED INTO MEMBERS TABLE
$stmt5 = $connection->prepare("INSERT INTO `conversations_members` (conversation_id, user_id, conversation_last_view, conversation_deleted)
VALUES (?, ?, ?, ?)");
$q = $stmt5->bind_param('iiii', $conversation_id, $recipient_id, $a, $b);
$stmt5->execute();
$stmt5->close();

PHP/MySQL: After inserting the value into a table the value of the variable gets lost and cannot print it out at the end of the file? [duplicate]

This question already has answers here:
Insert_id is null when used directly in next prepared statement
(2 answers)
Closed last year.
I want to do more than one database queries in the same file:
Create a user, select the UID of that newly created user, and assign to that same user a specific role.
After I get the UID from the newly created user I save that value into the $userID variable, but at the end of the file, the variable value gets lost.
Why? (PS: I'm not taking into account security at the moment).
//Create User
$email = strip_tags($_POST['email']);
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$query = "INSERT INTO usuarios
(userEmail)
VALUES
('$email')";
$insertarBase = mysqli_query($conectar,$query);
mysqli_close($conectar);
//look for the UID of the newly created user
$conectar2 = mysqli_connect(HOST, USER, PASS, DATABASE);
$buscarUsuario = "SELECT userID, userEmail
FROM usuarios
WHERE userEmail='$email'
";
$resultadoBusqueda = mysqli_query($conectar2,$buscarUsuario);
$row = mysqli_fetch_array($resultadoBusqueda);
$userID = $row['userID'];
mysqli_close($conectar2);
//assign a role to the newly created user
$conectar3 = mysqli_connect(HOST, USER, PASS, DATABASE);
$asignarRol = "INSERT INTO rolesUsuarios
(userID, nombreRol)
VALUES
('$userID', 'registered')
";
$asignarRolenBase = mysqli_query($conectar3,$asignarRol);
mysqli_close($conectar3);
echo $userID; //Here the content of $userID is gone, nothing gets printed out
Edited:
For some weird reason, $userID = mysqli_insert_id($conectar); returns zero.
The creation of the usuarios table statement is this:
CREATE TABLE usuarios(
userID int unsigned not null auto_increment primary key,
userEmail char(50) not null);
Also, echo $asignarRol; returns:
INSERT INTO rolesUsuarios (userID, nombreRol) VALUES ('0', 'noAutorizado')
i tried to tidy up your code and delete superfluous code.
//Create User
$email = $_POST['email']; // you have to verify if this is an email or html etc.
$conectar = new mysqli(HOST, USER, PASS, DATABASE);
$query = "INSERT INTO usuarios
(userEmail)
VALUES
(?)";
$stmt = $conectar->prepare($query);
$stmt->bind_param('s',$email);
$stmt->execute();
$userID = $stmt->insert_id;
$stmt->close();//close statement
//assign a role to the newly created user
$query = "INSERT INTO rolesUsuarios
(userID, nombreRol)
VALUES
(?, 'registered')";
$stmt = $conectar->prepare($query);
$stmt->bind_param('i',$userID);
$stmt->execute();
$stmt->close();
$conectar->close();
echo $userID; //Here the content of $userID
First of all , you don't have to create a new db-connection for each statement.
Second: please prepare your statements - for security purposes.
If $userID is empty, make an error_log($userID); after you $userID gets it value, if it's empty , there might be something else wrong.
First as other said to you use prepared statement for SQL injection and second the SQL connection not need to repeat so many time. Too many code and select not need please check the follow.
<?php
$conn = new mysqli(HOST, USER, PASS, DBNAME);
$insert_usuarios = $conn->prepare(" INSERT INTO usuarios ( userEmail ) VALUES ( ? ) ");
$insert_usuarios->bind_param( "s", $userEmail);
$insert_rolesUsuarios = $conn->prepare(" INSERT INTO rolesUsuarios ( userID, nombreRol ) VALUES ( ?, ? ) ");
$insert_rolesUsuarios->bind_param( "is", $userID, $nombreRol);
if(isset($_POST['email'])) {
$userEmail = $_POST['email'];
if (!$insert_usuarios->execute()) { // ERROR
echo('Error'); // OR ACTION THAT YOU LIKE
} else { // SUCCESS
$userID = $insert_usuarios->insert_id; // LAST ID INSERT
$nombreRol = 'REGISTERED';
if (!$insert_rolesUsuarios->execute()) { // ERROR
echo('Error'); // OR ACTION THAT YOU LIKE
} else { // SUCCESS
echo('Done!');
}
}
}
?>
Cheers!!!
Yet another cleanup of your code, following your code style and convention =)
//Create User
$conectar = mysqli_connect(HOST, USER, PASS, DATABASE);
$email = strip_tags($_POST['email']);
$query = 'INSERT INTO usuarios (userEmail) VALUES (?)';
$stmt = mysqli_prepare($conectar, $query);
mysqli_stmt_bind_param($stmt, 's', $email);
mysqli_stmt_execute($stmt); //execute query
$userID = mysqli_insert_id($conectar);
//assign a role to the newly created user
$query = "INSERT INTO rolesUsuarios (userID, nombreRol) VALUES (?, 'registered')";
$stmt = mysqli_prepare($conectar, $query);
mysqli_stmt_bind_param($stmt, 's', $userID);
mysqli_stmt_execute($stmt); //execute query
var_dump($userID);
tell me, what did you will get in the end?

Inserting Multiple values into MySQL database using PHP

I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.

Categories