Echo var before insert to database - php

Is it possible to show variable username before I am putting it into DB? Echo, alert, console or something? I want to check what is in $username before do INSERT
<?php
require_once 'connect.php';
$data = json_decode(file_get_contents("php://input"));
$username = mysqli_real_escape_string($connect, $data->username);
$query = "INSERT into tablename (username) VALUES ('$username')";
mysqli_query($connect, $query);
echo true;
?>

Try this
$username = mysqli_real_escape_string($connect, $data->username);
if($username)
{
echo $username;
$query = "INSERT into tablename (username) VALUES ('$username')";
mysqli_query($connect, $query);
}

<?php
require_once 'connect.php';
$data = json_decode(file_get_contents("php://input"));
$username = mysqli_real_escape_string($connect, $data->username);
$query = "INSERT into tablename (username) VALUES ('$username')";
echo "<script>alert('".$username."')</script>";
mysqli_query($connect, $query);
echo true;
?>

Related

PHP, MySQL Insert data from first table into second, third and fourth

I have one table called users (id, username, password), second table called profiles (id, user_id, username, name, lastname, age, gender, country, company_name), third table called companies (id, user_id, name, resources_id) and fourth table called resources (id, user_id, company_id, money). When users register their account, they need to create their profile. Now when they fill profile data, profiles and companies tables are filled just fine.
My problem is in resources table:
Error: Incorrect integer value: '' for column 'company_id' at row 1
When I refresh that page with error, resources table is filled fine, but now I got double rows for profiles and companies tables.
My Code :
<?php
session_start();
$dbserver = "localhost";
$dbusername = "root";
$dbpassword = "1234512345";
$db = "game";
$conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
if ($conn->connect_error)
{
die("Connection failed: ".$conn->connect_error);
}
if(isset($_SESSION['loggedin']))
$username = $_SESSION['loggedin'];
$query = "SELECT id FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$userId = $row['id'];
$_POST['id'] = $userId;
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$country = $_POST['country'];
$company_name = $_POST['company_name'];
$_POST['loggedin'] = $username;
$query = "SELECT id FROM companies WHERE name = '$company_name'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$companyId = $row['id'];
$_POST['id'] = $companyId;
//INSERT DATA INTO PROFILES
$sql = "INSERT INTO profiles (user_id, username, name, lastname, age, gender, country, company_name)
VALUES ('$userId', '$username', '$name', '$lastname', '$age', '$gender', '$country', '$company_name')";
//INSERT DATA INTO COMPANIES
$sql2 = "INSERT INTO companies (user_id, name)
VALUES ('$userId', '$company_name')";
//INSERT DATA INTO RESOURCES
$sql3 = "INSERT INTO resources (user_id, company_id)
VALUES ('$userId', '$companyId')";
if($conn->query($sql) && $conn->query($sql2) && $conn->query($sql3) === TRUE)
{
header("Location: ../../index.php?page=profile");
die();
}
else
{
echo "Error: ".$conn->error;
}
?>
What should I do differently? I'm still beginner into this, sorry for long post.
EDIT:
One guy helped me out with this code, it's more error proof than last version. Deleted companies table, merged it with profiles, now everything works correctly!
<?php
session_start();
$dbserver = "localhost";
$dbusername = "root";
$dbpassword = "1234512345";
$db = "game";
$conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
if ($conn->connect_error)
{
die("Connection failed: ".$conn->connect_error);
}
if(isset($_SESSION['loggedin']))
$username = $_SESSION['loggedin'];
$query = "SELECT id FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$userId = $row['id'];
$_POST['id'] = $userId;
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$country = $_POST['country'];
$company_name = $_POST['company_name'];
$_POST['loggedin'] = $username;
$query = "SELECT id FROM companies WHERE name = '$company_name'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$sql1 = "INSERT INTO profiles (user_id, username, name, lastname, age, gender, country, company_name) VALUES (?,?,?,?,?,?,?,?)";
$sql2 = "INSERT INTO resources (user_id) VALUES (?)";
try {
$conn->autocommit(false);
$statement = $conn->prepare($sql1);
$statement->bind_param("dsssdsss", $userId, $username, $name, $lastname, $age, $gender, $country, $company_name);
$statement->execute();
$statement = $conn->prepare($sql2);
$statement->bind_param("d", $userId);
$statement->execute();
// COMMIT THE CHANGES
$conn->commit();
header("Location: ../../index.php?page=profile");
}
catch(Exception $e){
// undo everything that was done in the try block in the case of a failure.
$conn->rollback();
echo "Error: ".$conn->error;
}?>

I cant´t add data to my database

Godd night. I have this code for php to add data to my database but i dont get succes.
<?php
require("config.inc.php");
if (!empty($_POST)) {
$user = $_POST['User'];
$mail = $_POST['Mail'];
$token = $_POST['Token'];
$pass = $_POST['Pass'];
$result = mysqli_query($con,"SELECT 1 FROM Proteos where
User='$user'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data==0){
echo $data;
echo "Hey, un grato saludo mister ".$user."!\n";
$query = "INSERT INTO Proteos (User, Mail ) VALUES ($user,$mail ) ";
}
mysqli_close($con)
And this is my config.inc
<?php
define('DB_SERVER','mysql.smartfreehosting.net');
define('DB_NAME','u178665800_prote');
define('DB_USER','u178665800_carin');
define('DB_PASS','xxxxxx');
$con = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
mysql_select_db(DB_NAME,$con);
?>
Put your value in single quote And than execute query
$query = "INSERT INTO Proteos (User, Mail ) VALUES ($user,$mail ) ";
to
$query = "INSERT INTO Proteos (User, Mail ) VALUES ('$user','$mail') ";
And after that pass $query to mysqli_query like
mysqli_query($con,$query);
String values have to be passed in quotes. Also execute the query .
To debug use mysqli_error
$query = "INSERT INTO Proteos (User, Mail ) VALUES ('{$user}','{$mail}' ) ";
mysqli_query($con,$query);
or
mysqli_query($conn, $query) or die(mysqli_error($conn));
to connect with mysqli (ref) change in config.inc
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS, DB_NAME);
You are inserting VARCHAR (string) data into Database without single quotes.
Data without single quotes is considered as either table/field names or integers or keywords.
Your entered data being none of these is causing errors.
Corrected SQL:
$query = "INSERT INTO Proteos (User, Mail ) VALUES ('$user','$mail') ";
<?php
require("config.inc.php");
if (!empty($_POST)) {
$user = $_POST['User'];
$mail = $_POST['Mail'];
$token = $_POST['Token'];
$pass = $_POST['Pass'];
$result = mysqli_query($con,"SELECT 1 FROM Proteos where
User='$user'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data==0){
echo $data;
echo "Hey, un grato saludo mister ".$user."!\n";
mysqli_query($con,"INSERT INTO Proteos (User, Mail ) VALUES ('$user','$mail' ) ") or die(mysqli_error());
}
mysqli_close($con);
check above code, values are insert using 'var' like '$user','$mail'
any error shows in the query helps to find the code or die(mysqli_error())

PHP and SQL(Trying to update my database using submit button)

I am trying to update my feedback in my SQL database form with help of submit button but I'm unable to do so. Please help!
if (isset($_POST['submitreport']))
{
$dbCon = mysqli_connect("localhost","root","","Hun");
$report = strip_tags($_POST['report']);
$sql = "UPDATE Feedback SET report='$report' WHERE username='$username' AND date='$date' ";
$query = mysqli_query($dbCon, $sql);
}
<?php
if (isset($_POST['submitreport']))
{
$monthDayYear = date('m-d-Y');
$dbConnnection = mysqli_connect("localhost","root","","Hun");
$dbUsername = strip_tags($_POST['report']);
$sqlQuery = "UPDATE Feedback SET report='".$report."' WHERE username='".$username."' AND date='".$monthDayYear."'";
$queryExecute = mysqli_query($dbConnection, $sqlQuery);
}
?>
<?php
if (isset($_POST['submitreport']))
{
$dbCon = mysqli_connect("localhost","root","","Hun");
$username = 'test';
$report = strip_tags($_POST['report']);
$date = date('m-d-Y');
$sql = "UPDATE Feedback SET report='".$report."' WHERE username='".$username."' AND date='".$date."'";
$query = mysqli_query($dbCon, $sql);
}
?>

MySQL insert username and password via php error

MySQL is not inserting the correct username and password in the database. The php code is:
<?php
$username = $_POST["email"];
$password = $_POST["password"];
require 'database.php';
$myquery = "INSERT INTO verify (`username`, `password`) VALUES ('$username','$password')";
$query = mysql_query($myquery);
if (!$query) {
echo mysql_error();
die;
}
?>
I checked the database.php, it is absolutely fine. It is showing username and password as pranav even though the values are different.
Thanks in advance.
Try to re-order you code, maybe some vars are overwritting his values:
<?php
require 'database.php';
$username = $_POST["email"];
$password = $_POST["password"];
$myquery = "INSERT INTO verify (`username`, `password`) VALUES ('$username','$password')";
$query = mysql_query($myquery);
if (!$query) {
echo mysql_error();
die;
}
?>
I found out what the error was . It was happening because the database.php was coded like this.
PHP:
<?php
$username="pranav";
$password="pranav";
$host="localhost";
$database="requester";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db ($database, $server);
$table='verify'
?>
The username and password was getting rewritten.
Thanks Grommy

sql update error afer registration

After creating a form for user registration, I want to add groups.
Now I first tried editing the prepared statement but that did not work, so I tried this:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
include('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST["username"]) && isset($_POST["password"])){
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$epassword = hash("sha512", $password);
$group = 'user';
$query1 = "SELECT * FROM `user` WHERE email='$email'";
$result = mysqli_query($connection, $query1) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
$msg1 = "Dit E-mailadres is al in gebruik voor een andere gebruiker.";
}else{
$query = "SELECT * FROM `user` WHERE username='$username'";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
$msg2 = "Deze gebruikersnaam is al in gebruik.";
}else{
$stmt = $connection->prepare("INSERT INTO `user` (username,password,email) VALUES(?,?,?)");
$stmt->bind_param("sss", $username, $epassword, $email);
$stmt->execute();
$msg = "De gebruiker is aangemaakt.";
$sql2 = "UPDATE user
SET group = $group
WHERE username = $username" ;
$retval = mysqli_query( $connection, $sql2);
if(! $retval )
{
die('Could not update data: ' . mysqli_error($connection));
}
}
}
}
?>
and now it is creating the user (with no group) after showing the following error:
Could not update data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group = user WHERE username = test' at line 1
could you help me with this?
thanks to juergen d this is the working code:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
include('connect.php');
// If the values are posted, insert them into the database.
if (isset($_POST["username"]) && isset($_POST["password"])){
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$epassword = hash("sha512", $password);
$modus = "user";
$query1 = "SELECT * FROM `user` WHERE email='$email'";
$result = mysqli_query($connection, $query1) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
$msg1 = "Dit E-mailadres is al in gebruik voor een andere gebruiker.";
}else{
$query = "SELECT * FROM `user` WHERE username='$username' ";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
$msg2 = "Deze gebruikersnaam is al in gebruik.";
}else{
$stmt = $connection->prepare("INSERT INTO `user` (username,password,email) VALUES(?,?,?)");
$stmt->bind_param("sss", $username, $epassword, $email);
$stmt->execute();
$msg = "De gebruiker is aangemaakt.";
$sql2 = "UPDATE `user`
SET `modus` = '$modus'
WHERE username = '$username'";
$retval = mysqli_query( $connection, $sql2);
if(! $retval )
{
die('Could not update data: ' . mysqli_error($connection));
}
}
}
}
?>
group is a reserved word and needs to be escaped with backticks.
UPDATE user
SET `group` = '$group'
WHERE username = '$username'"
And as others already mentioned - put your strings in quotes or better look into Prepared Statements.
You need to wrap strings in apostrophes, just like you did in one of your previous queries; example:
$sql2 = "UPDATE `user` SET `group` = $group WHERE username = '$username'";
Also, as per juergen d's answer, you need to enclose the group column in backticks, as it is a reserved word.
I don't know whether mysql allow you to use "group" as column name, but the most obvious error is you need wrap the group value with double quotes: set group="$group"
try:
$sql2 = "UPDATE `user`
SET `group` = '$group'
WHERE `username` = '$username'";

Categories