Php and Mysql communication [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
i've Apach2, Mysql and php (also php-mysql); i'm trying to insert from a form (varchar, varchar, password, date, varchar)into the table utenti in my db music:
Describe Utenti
I'm using procedural style mysqli: It says me "Insert success" but it doesn't write for real on the Db;
<?php
$nome = $_POST['nome'];
$cognome = $_POST['cognome'];
$password = $_POST['password'];
$datanascita = $_POST['datanascita'];
$email = $_POST['email'];
$host = "localhost";
$user = "root";
$password = "popolo";
$dbname = "music";
//Connessione
$con = mysqli_connect($host, $user, $password, $dbname);
//verifica eventuali errori
if (mysqli_connect_errno()) {
echo "Connesione fallita" . mysqli_connect_error();
exit();
} else {
echo "Connected \n";
//Inserting record in table using INSERT query
$mysqli = "INSERT INTO Utenti (`nome`, `cognome`, `password`, `datanascita`, `email`)
VALUES ($nome, $cognome, $password, $datanascita, $email)";
mysqli_query($conn, $mysqli);
echo "Insert success";
}
mysqli_close($conn);
?>

whatever your query succeeded or not this message echo "Insert success"; will output, you should check if your query succeeded first , you must your varchar in 2 '
$mysqli = "INSERT INTO Utenti (`nome`, `cognome`, `password`, `datanascita`, `email`)
VALUES ('$nome', '$cognome','$password', '$datanascita', '$email')";
you can check like this:
$result = mysqli_query($conn,$mysqli);
if($result){
echo "Insert success";
} else {
echo "Insert failed, Error: ".$mysqli->error;
}

Related

How to query variable from database using php

Good Day developers outthere! 😊😊
I just wanna ask what is the problem with my code, I'm trying to make a webpage using html,css,php and database. Now I already created a php in my html form and my database is already connected, but everytime I submit the information in the html form I created, nothing appeared in my database.
<?php
if(isset($_POST['save'])){
$FName = $_POST['FName'];
$MName = $_POST['MName'];
echo "Successfully Added";
$sql= "INSERT INTO 'tbstudinfo' (Transaction_Number, First_Name, `Middle_Name') VALUES ('000',$FName,$MName)";
} else{
echo "<p>Insertion Failed.</p>";
}
?>
Just as #executable mentioned, you are defining query in your code but not executing it.
Define Connection Object (Mysqli, PDO..)
Prepare Query and Bind Variables
Execute your query
Here's an example using prepared statements
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset($_POST['save']) ){
// prepare and bind
$stmt = $conn->prepare("INSERT INTO 'tbstudinfo' (Transaction_Number, First_Name, Middle_Name) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $transaction_number, $FName, $MName);
// set parameters and execute
$transaction_number = '000';
$FName= $_POST['FName'];
$MName= $_POST['MName'];
$stmt->execute();
echo "Successfully Added";
}else{
echo "<p>Nothing Posted</p>";
}
W3Schools and PHP.Net both have pretty good examples about how to use prepared statements to make your SQL Query more secure from SQL Injections.
You simply don't execute your query. Using MySQLi :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "dbthesis";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['save'])){
$FName = $_POST['FName'];
$MName = $_POST['MName'];
$sql = "INSERT INTO tbstudinfo (Transaction_Number, First_Name, Middle_Name) VALUES ('000', '$FName', '$MName')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Added";
} else {
echo "<p>Insertion Failed.</p>";
}
}
$conn->close();
You only making a query, not running query. This this code
$FName = $_POST['FName'];
$MName = $_POST['MName'];
$sql = "INSERT INTO tbstudioinfo (Transaction_Number, First_Name, Middle_Name) VALUES ('000','$FName','$MName')";
// code below runs your query
if (mysqli_query($conn, $sql)) {
echo "Successfully Added";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

Data is not inserting on the database Game resgistration

So im making a web game app my problem is my register.php is not inserting users in the database please need help by the way im just a beginner in PHP Thanks
Here is the Code:
<?php
require_once('mysql_conn.php');
$Username = mysql_real_escape_string($_POST['Username']);
$Password = md5(mysql_real_escape_string($_POST['Password']));
$Email = mysql_real_escape_string($_POST['Email']);
$query_check ="SELECT user_name FROM account_info WHERE user_name = '$Username'";
$retval_check = mysql_query( $query_check, $conn );
if( $Username == "" || $Password == "" || $Email == "" ){
echo"Please fill the field";
} else{
if(mysql_num_rows($retval_check)){
echo"Username Already Taken";
} else {
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
$retval = mysql_query( $query, $conn );
echo "<script>";
echo "alert('Thank you for registering Enjoy the game !')";
echo "</script>";
echo "<script>";
echo 'location.href = "menu.html";';
echo "</script>";
}
}
mysql_close($conn);
?>
Change:
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
To:
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
You forgot to add a comma ","
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
YOu miss the coma between user_pass and email in column name
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
try mysqli
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
//require_once('mysql_conn.php');
$Username = mysqli_real_escape_string($_POST['Username']);
$Password = md5(mysqli_real_escape_string($_POST['Password']));
$Email = mysqli_real_escape_string($_POST['Email']);
//$query_check ="SELECT user_name FROM account_info WHERE user_name = '$Username'";
// $retval_check = mysqli_query( $query_check, $conn );
if(!empty($Username))
{
$stmt = $conn->prepare("SELECT user_name FROM account_info WHERE user_name =? ");
$stmt->bind_param('s',$Username);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$get_result =$stmt->get_result();
$row_count= $get_result->num_rows;
//$row_count= $stmt->affected_rows;
$stmt->close();
//$conn->close();
}
if( $Username == "" || $Password == "" || $Email == "" ){
echo"Please fill the field";
} else{
if($row_count>0){
echo"Username Already Taken";
} else {
//$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email');";
^^^^^
//$retval = mysql_query( $query, $conn );
$stmt1 = $conn->prepare("INSERT INTO account_info(user_name,user_pass,email) VALUES (?,?,?)");
$stmt->bind_param('sss',$Username,$Password,$Email);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt1->execute();
//$get_result1 =$stmt1->get_result();
//$row_count1= $get_result1->num_rows;
$row_count1= $stmt1->affected_rows;
$stmt1->close();
$conn->close();
if($row_count1>0)
{
echo "<script>";
echo "alert('Thank you for registering Enjoy the game !')";
echo "</script>";
}
else
{
echo "<script>";
echo "alert('registeration failed')";
echo "</script>";
}
echo "<script>";
echo 'location.href = "menu.html";';
echo "</script>";
}
}
wrong
$query = "INSERT INTO account_info(user_name,user_passemail) VALUES ('$Username','$Password','$Email');";
correct
$query = "INSERT INTO account_info(user_name,user_pass,email) VALUES ('$Username','$Password','$Email')";

mysqli insert, what is wrong?

the data is not inserting. i think there is something wrong in
$sql = "INSERT INTO `users` (`Username`, `Password`, `FirstName`, `LastName`, `Email`, `ContactNumber`)
VALUES ('".$_POST["Username"]."','".$_POST["Password"]."','".$_POST["FirstName"]."','".$_POST["LastName"]."','".$_POST["Email"]."','".$_POST["ContactNumber"]."')";
When i try to change the statement in "else" with echo "successs"; its working.
please someone can tell me what is wrong.
<?php
error_reporting(E_ALL & ~E_NOTICE);
if(isset($_POST["Register"]))
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbuseraccounts";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user = $_POST['Username'];
$pass = $_POST['Password'];
$query = mysqli_query($conn, "SELECT * FROM users WHERE Username= '".$user."'");
if(mysqli_num_rows($query) > 0)
{
echo "email already exists";
}
else
{
$sql = "INSERT INTO users (Username, Password, FirstName, LastName, Email, ContactNumber)
VALUES ('".$_POST["Username"]."','".$_POST["Password"]."','".$_POST["FirstName"]."','".$_POST["LastName"]."','".$_POST["Email"]."','".$_POST["ContactNumber"]."')";
}
$conn->close();
}
?>
Your data is not inserting because you haven't even executed your query.
if (mysqli_num_rows($query) > 0) {
echo "Username already exists";
} else {
$sql = "INSERT INTO users (Username, Password, FirstName, LastName, Email, ContactNumber) VALUES ('".$_POST["Username"]."','".$_POST["Password"]."','".$_POST["FirstName"]."','".$_POST["LastName"]."','".$_POST["Email"]."','".$_POST["ContactNumber"]."')";
/* Run your query and check for errors */
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
}
Please Execute query using
mysqli_query($conn, your query);

PHP & mySQL obtaining last insert ID

I'm quite new to this php/mysql deal and I'm having a hard time figuring out this situation particularily.
I have two tables, one of them is "dog" table and the other one is the "date" table. In order to insert a record in the "dog" table I MUST first insert a date in the "table" date and get the autoincrement id from that date.
Problem is that I've tried reading several posts on how to get the last insert id from a table you just inserted a record on and I can't seem to make it work.
$sql1="INSERT INTO FECHAS (fecha) VALUES (NOW())";
mysql_query($sql1);
echo $sql1;
$sql3="SELECT LAST_INSERT_ID()";
mysql_query($sql3);
echo $sql3;
$sql2="INSERT INTO PERRO (nombre_perro,FECHAS_id_fecha) VALUES ('$nombre_perro_var', '$last_id')";
echo $sql2;
if (!$mysqli->query($sql2)) {
echo 'Error: ', $mysqli->error;
}
$result2 = mysql_query($sql2);
Please forgive this code, I'm new and learning.
Thanks!
Use mysqli instead of mysql_
Connecting with mysqli:
$connection = mysqli_connect($hostname, $username, $password, $database_name);
Inserting into a table:
mysqli_query($connection, $sql);
Retrieving last inserted id:
$id = mysqli_insert_id($connection);
**Database**
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
**Example (MySQLi Object-oriented)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
***$last_id = $conn->insert_id;***
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
**Example (MySQLi Procedural)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
***$last_id = mysqli_insert_id($conn);***
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
**Example (PDO)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
***$last_id = $conn->lastInsertId();***
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
A procedural solution (although it might be slightly wrong - I'm terrible at PHP)...
<?php
include('path/to/connection/stateme.nts');
$query = "
INSERT INTO fecha (fecha) VALUES (NOW());
";
mysqli_query($db,$query);
$query = "
INSERT INTO perro (nombre_perro,id_fecha) VALUES (?,?);
";
$nombre_perro = 'rover';
$id_fecha = mysqli_insert_id($db);
$stmt = mysqli_prepare($db,$query);
mysqli_stmt_bind_param($stmt, 'si', $nombre_perro,$id_fecha);
mysqli_stmt_execute($stmt);
?>
You might consider binding both queries into a transaction, so that in the event that the second query fails for some reason, then the first query fails too.

return last inserted id doesn't work in php

$result = $db->query("INSERT INTO post_items(`post_id`,`content`,`date`,`user_id`,`category_id`)
VALUES ('', '".$content."', '".$date."', '".$user_id."', '".$category_id."')");
if($result) {
echo mysql_insert_id();
}else{
echo "Something is wrong. Insert failed..";
}
my post_id is an auto increment field. It gave me a '0' instead of the last inserted id.
In case your query really worked (please verify that...) you're probably mixing the outdated mysql connector and the mysqli connector. mysql_insert_id() is the function from the mysql connector. Use mysqli_insert_id() instead.
Try
if($result) {
echo $db->insert_id;
}else{
echo "Something is wrong. Insert failed..";
}
Database
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
last inserted ID:
-------------------------------------------------------------------
1. Example (MySQLi Object-oriented)
-------------------------------------------------------------------
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
-------------------------------------------------------------------
2. Example (MySQLi Procedural)
-------------------------------------------------------------------
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
-------------------------------------------------------------------
3. Example (PDO)
-------------------------------------------------------------------
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Don't include post_id when inserting a new row since it is auto_increment.

Categories