MySQLi insert statement to executing - php

I am writing a simple code in PHP to test my MySql server by , inserting data to my database server
i am executing the file from the internet
URL of executing : Scores2.php?n=asdad&l=345&s=241
PHP Code:
<?php
$servername = "sql3.freesqldatabase.com";
$username = "MY USERNAME";
$password = "MY PASSWORD";
$dbname = "MY DBNAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES ($name, $score, $level)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When i execute the file , the browser shows this error :
Error: INSERT INTO HighScores (name, score, level) VALUES (asdad, 241, 345)
Unknown column 'asdad' in 'field list'
I checked the Control Panel in phpMyAdmin and executed the same statement but without variables , and it worked
Rows Types :
name : text
score : int(11)
level : int (11)

Learn how to prepare the query it's not that difficult.
You will avoid sql injection and missing quotes
Use num_rows to check if the record is inserted
Use $conn->error if the prepare() call return false.
$name = (string)$_GET['n'];
$score = (int)$_GET['s'];
$level = (int)$_GET['l'];
$sql = "INSERT INTO HighScores (name, score, level)
VALUES (?, ?, ?)";
if ($stmt = $conn ->prepare($sql)) {
$stmt->bind_param("s", $name);
$stmt->bind_param("i", $score);
$stmt->bind_param("i", $level);
$stmt->execute();
if($stmt->num_rows > 0){
echo "New record created successfully";
}else{
echo "no rows affected";
}
$stmt->close();
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn ->close();

$sql = "INSERT INTO HighScores (name, score, level)
VALUES ('$name', '$score', '$level')";
change query like this

Related

INSERT TABLE using php variable

What is the correct syntax for the SQL INSERT INTO when using a php variable for table name. I have tried everything and it won't insert when I use php variable.
This is what I have so far. is this right?
$sql = "INSERT INTO ".$table." (`Name`) VALUES ('A')";
mysqli_query($conn, $sql);
if I switch $table to the actual table name, it works
$sql = "INSERT INTO 'myTable' ('Name') Values ('A')";
It works for me fine
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stack_over_flow";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
When Table Name is Variable
$DB_TBLName = "abc";
$sql_ac_valuee = "INSERT INTO $DB_TBLName (a, b ,c) VALUES "."('10','20','30')";
if ($con->query($sql_ac_valuee) === TRUE) {
}
else{
echo "Error: " . $sql_ac_valuee . "<br>" . $con->error;
}
When Use direct Table Name
$sql_ac_valuee = "INSERT INTO abc (a, b ,c) VALUES "."('10','20','30')";
if ($con->query($sql_ac_valuee) === TRUE) {
}
else{
echo "Error: " . $sql_ac_valuee . "<br>" . $con->error;
}
$query = "INSERT INTO $tname (place,dis,p_1,p_2,p_3,p_4,p_5,p_6) VALUES('$name','$discription','$bfile','$file1','$file2','$file3','$file4','$file5')";
$result =mysqli_query($link,$query);
if(!$result){echo mysqli_error($link);?>
This was my code and the output is:
Skardu.You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(place,dis,p_1,p_2,p_3,p_4,p_5,p_6) VALUES('Sundus','Few people can afford the T' at line 1
its work fine when i use skardu instead of varible

Why does the following not appear to open an SQL connection?

I find that the folowing script hangs for some reason. It will load and PHP doesn't see any errors, but it will not process the data (noting that we are in a context where I have a seperate login database open.)
In process.php we have the following:
<? PHP
//Process the POST data in prepration to write to SQL database.
$_POST['chat_input'] = $input;
$time = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_SESSION['username'];
$servername = "localhost";
$username = "id3263427_chat_user";
$password = "Itudmenif1!Itudmenif1!";
$dbname = "id3263427_chat_user";
$id = "NULL";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = 'INSERT INTO `chat` (`id`, `username`, `ip`, `timestamp`,
`message`) VALUES ('$id','$name', '$ip', '$time', '$input')';
if(mysqli_query($link, $sql)){
mysqli_close($conn);
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
the html form passed to the script above is as follows:
<form action="/process.php" method="post" id="chat">
<b> Send A Message (500 Character Max):</b><br>
<textarea name="chat_input" form="chat" size="500"></textarea>
<input type="submit" value=submit>
</form>
Not sure what's going on with this.
You got the syntax error because you're closing the $sql string before $id with your '.
What is this about your $id variable? With your current code you will insert the String "NULL". If you want to set the sql value null you should use $id = null; or just don't insert any value.
If you want your database to set an id, also leave it blank.
$input = $_POST['chat_input'];
$id = null;
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("ERROR: Could not connect. " . $conn->connect_error);
}
First solution
If this isn't a production code, you could insert the variables directly into the statement, but you should use " instead of ' for your sql string, so you can insert variables and ' without closing the string.
$sql = "INSERT INTO chat (id, username, ip, timestamp, message) VALUES ('$id', '$name', '$ip', '$time', '$input')";
if($conn->query($sql) === true) {
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " .$conn->error;
$conn->close();
}
Second solution
A better approach would be a prepared statement.
$stmt = $conn->prepare('INSERT INTO chat (username, ip, timestamp, message) VALUES (?, ?, ?, ?)');
$stmt->bind_param("ssss", $username, $ip, $time, $input);
if($stmt->execute()) {
$stmt->close();
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $stmt. " . $conn->error;
$stmt->close();
$conn->close();
}
The "s" in bind_param() defines a string at the given position, if you want to insert an integer, use "i" instead.
e.g. bindParam("sis", $string, $integer, $string);

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.

PHP / MySQL: How to return info if record already exists (without update)

I am using the below to insert a new row into a MySQL db.
The query for this is stored in a PHP file (ajax.php) and the input values are passed to this via an Ajax call in jQuery.
Everything works as intended but I would like to return a message to the user if an email is already in the db.
I know how to update a db row using ON DUPLICATE KEY but can someone tell me how I can just check for this and echo something if it exists there already (i.e. without updating it) ?
(email is a single primary key so I only need to check for this column.)
My PHP:
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$dob = $_POST["dob"];
$sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')";
if ($conn->query($sql)){
echo 'DB Update successful';
}else{
echo 'DB Update failed';
}
$conn->close();
You just need a simple SELECT call before inserting.
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$dob = $_POST["dob"];
$sql = "SELECT email FROM Users WHERE email = " .$email;
$query = $conn->query($sql);
if (mysqli_num_rows($query) > 0){
echo "There exists an user with this email";
}
else {
$sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')";
if ($conn->query($sql)) {
echo 'DB Update successful';
}
else {
echo 'DB Update failed';
};
}
$conn->close();
The simple way is just to count the occurances of entries in the table with the same email as you are trying to store. Counting rather than SELECTing means it is quicker and only a count is returned not a complete row that you have to then look at or count the rows in the result.
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $Conn->prepare("Select Count(email) as cnt FROM Users WHERE email = ?");
$stmt->bind_param('s', $_POST["email"]);
$stmt->execute();
$stmt->bind_result($cnt)
$stmt->close();
if ( $Cnt > 0 ) {
// its already there so do whatever you want in this case
} else {
$sql = "INSERT INTO Users (email, dob) VALUES (?,?)";
$stmt = $Conn->prepare($sql);
$stmt->bind_param('ss', $_POST["email"],$_POST["dob"]);
if ($stmt->execute(){
echo 'DB Update successful';
}else{
echo 'DB Update failed';
}
}
$conn->close();

Call to a member function execute() on a non-object in

I have the following error, and this is the exact same form processing file I use for registering a user, but I changed it for the appropriate table and columns. While the reg works fine every time.
Here is the code where the error is located:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
Here is the full code:
<?php
$servername = "localhost";
$username = "root";
$password = "Af2vaz93j68";
$dbname = "pdo_ret";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$eventname = $_POST['eventname'];
$about = $_POST['about'];
$website = $_POST['website'];
if($eventname == '') {
$errmsg_arr[] = 'You must enter your Email';
$errflag = true;
}
if($about == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
if($website == '') {
$errmsg_arr[] = 'You must enter First Name';
$errflag = true;
}
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Youre confusing PDO and mysqli. mysqli does not support named parameters so you stmt is not compiling and Mysqli::prepare is returning false. Additionally mysqli does not support passing the param to be bound through mysqli_stmt::execute so even if you switch to positional placeholders your execute will fail.
This is what you would need for mysqli:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
// check to make sure the statement was prepared without error
if ($stmt) {
// the statement is good - proceed
$stmt->bind_param('sss', $eventname, $about, $website);
$stmt->execute();
}
Additionally this makes no sense at all:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will just run the same query again either inserting a second row of the exact same data, or perhaps creating a duplicate key error depending upon your schema.
If you want to test that the previous query succeeded you would do something like:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
if ($stmt) {
$stmt->bind_param('sss', $eventname, $about, $website);
$success = $stmt->execute();
} else {
$success = false;
}
if ($success === true) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
If you want to use PDO (which i prefer and usually recommend) your code would look something like this:
$conn = PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
echo "New record created successfully";
} catch (PDOException $e) {
echo "Error: " . $sql . "<br>" . $e->getMessage();
}

Categories