I've got the code to insert correctly, but am failing to get it to give me a success message. It always returns failed to add the device to the database, but then I go check the database and it is in fact successfull. Any ideas?
<?php
// Start or resume the session
session_start();
//Check to ensure the user is authorized to view this page
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
// Include Header
include("includes/header.php");
echo "
<div class='form_description'>
<h2>French Lick Resort</h2>
<p>STATUS - Add Ingenico Device to Inventory</p>
</div>
<form id='update' class='fieldset' method='post' action=''>";
$serial=$_POST['serial'];
$model=$_POST['model'];
$deviceCondition=$_POST['deviceCondition'];
$sealCondition=$_POST['sealCondition'];
$location=$_POST['location'];
$deployDate=$_POST['deployDate'];
$weight=$_POST['weight'];
$notes=$_POST['notes'];
//NEW PDO connection
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "INSERT INTO web01dev4s2.ingenicoInfo (serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes) VALUES ('".$serial."', '".$model."', '".$deviceCondition."', '".$sealCondition."', '".$location."', '".$deployDate."', '".$weight."', '".$notes."')";
$q = $conn->prepare($sql);
$result_1=mysql_query($sql);
$q->execute();
}
catch (PDOEException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
//End pdo connection
// Display "GO" or "NO GO"
if($result_1){
echo "Device successfully added to the database.";
header( "refresh:2;url=devicelist.php" );
}
else {
echo "Failed to add the device to the database. Please ensure that the device is not already in the database and that all fields are filled out. Notes should be NA if there are no notes to add. Also, ensure the name does not containt any special characters such as quotes.<br />";
Echo "<a href=create.php>Back</a>" ;
}
}
else {
header('Location:login.php');
}
echo "
</form>
</div>
</body>
</html>";
?>
You are mixing your use of PDO and the mysql extension. Don't do that.
If you are going to use PDO, use the prepare statements correctly, as well. You should not put your variables into the raw SQL string, instead use '?' where you expect a value to be inserted. Then pass an array of variables into the statement's execute. This is the PDO way, and it will help prevent SQL injections against your code.
$sql = "INSERT INTO web01dev4s2.ingenicoInfo (serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$q = $conn->prepare($sql);
// This line should fix your problem
$result_1 = $q->execute(array($serial, $model, $deviceCondition, $sealCondition, $location, $deployDate, $weight, $notes));
Related
This question already has answers here:
how to use $_GET inside mysqli_query? [duplicate]
(7 answers)
PHP: Inserting Values from the Form into MySQL
(2 answers)
PHP MySQLInsert prepared statements
(4 answers)
Closed last year.
I created a prepared statement in my PHP script but when I submit my form to insert, I get this error, Fatal error: Uncaught TypeError: mysqli_query(): Argument #2 ($query) must be of type string, mysqli_stmt given in C:\xampp\htdocs\7058\insert.php:100 Stack trace: #0 C:\xampp\htdocs\7058\insert.php(100): mysqli_query(Object(mysqli), Object(mysqli_stmt)) #1 {main} thrown in C:\xampp\htdocs\7058\insert.php on line 100.
It is my first time trying prepared SQL statements, so I am not sure what I am doing wrong.
<?php
session_start();
// servername => localhost
// username => root
// password => empty
// database name => staff
$conn = mysqli_connect("localhost", "root", "", "survey");
// Check connection
if ($conn === false) {
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
$name = $_SESSION['name'];
$paygoid = $_SESSION['paygoid'];
$product_exist_satisfaction = $_SESSION['product_exist_satisfaction'];
$system_battery_runout = $_SESSION['system_battery_runout'];
$rank_appliances = $_POST['rank_appliances']; //return an array.
$checkboxvalue = implode(",", $rank_appliances);
$sql = $conn->prepare("INSERT INTO cus_survey (name,paygoid,product_exist_satisfaction,system_battery_runout,rank_appliances) VALUES (?, ?, ?, ?, ?)");
$sql->bind_param("sssss", $name, $paygoid, $product_exist_satisfaction, $system_battery_runout, $checkboxvalue);
if (mysqli_query($conn, $sql)) { **//this is line 97**
echo "<h3>Your survey was captured successfully. Thank You!"
} else {
echo "<h3>Sorry, Your ID has already been used. Please enter a valid ID</h3> "
echo "<h3><a href='/7058/index.php'>Click here to edit your ID</a></h3>";
}
// Close connection
mysqli_close($conn);
?>
I hope the following will help point you in the right direction. Initially you should make a sanity check that the variables you intend to use are actually available to avoid silly errors and then, using the considerably less verbose OO style of mySQLi, prepare the sql statement, bind the placeholders, execute the statement and then find if it succeeded.
<?php
session_start();
if( isset(
$_SESSION['name'],
$_SESSION['paygoid'],
$_SESSION['product_exist_satisfaction'],
$_SESSION['system_battery_runout'],
$_POST['rank_appliances']
)){
$conn = new mysqli("localhost", "root", "", "survey");
$name = $_SESSION['name'];
$paygoid = $_SESSION['paygoid'];
$product_exist_satisfaction = $_SESSION['product_exist_satisfaction'];
$system_battery_runout = $_SESSION['system_battery_runout'];
$rank_appliances = $_POST['rank_appliances'];
$checkboxvalue = implode(",", $rank_appliances);
$stmt = $conn->prepare( "INSERT INTO `cus_survey` ( `name`, `paygoid`, `product_exist_satisfaction`, `system_battery_runout`, `rank_appliances` ) VALUES (?, ?, ?, ?, ?)" );
$stmt->bind_param("sssss", $name, $paygoid, $product_exist_satisfaction, $system_battery_runout, $checkboxvalue );
$stmt->execute();
if ( $stmt->affected_rows==1 ) {
echo "<h3>Your survey was captured successfully. Thank You!"
} else {
echo "<h3>Sorry, Your ID has already been used. Please enter a valid ID</h3> "
echo "<h3><a href='/7058/index.php'>Click here to edit your ID</a></h3>";
}
$stmt->close();
$conn->close();
exit();
}
?>
I have code
<form action="insert1.php" form method="POST">
<input type="text" name="product" /></p>
<input type="submit" value="Add">
And
$mysqli = configuration();
$product = $_REQUEST['$product'];
$sql = "INSERT INTO Odiet (product) VALUES ('$product')";
if($mysqli ->query($sql)===TRUE){echo "ok";}
else{echo "not ok";}
$mysqli ->close();
It adds empty string without text.
Please help.
Thanks.
Replace this string:
$product = $_REQUEST['$product'];
With this
$product = $_REQUEST['product'];
You should know which one to use, $_REQUEST opens up a huge security risk to your database. Also use preprared statements.
$sql = "INSERT INTO Odiet (product) VALUES (?)";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("s", $_POST['product']);
if($stmt->execute()){
echo "ok";
} else {
echo "not ok";
}
}
There is also little use in closing the db connection as this is automatically done after script execution.
I just fix one error in you code and you need to put it like this:
$mysqli = configuration();
$product = $_REQUEST['product'];
$sql = "INSERT INTO Odiet (product) VALUES ('$product')";
if($mysqli ->query($sql)===TRUE){echo "ok";}
else{echo "not ok";}
$mysqli ->close();
You get values from html form by field name, but without dolar sign before.
And be aware that your code is not safe. Don't put raw user data in your sql statement, use prepared statements instead
I want import a data (from a form) in my database but i've this error :
Parse error: syntax error, unexpected ';' in /homepages/38/htdocs/index2.php on line 7
and the script is
<?php
//Connecting to sql db.
$connect = mysqli_connect("","","","");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO posts (email, pseudo)
VALUES ('$_POST[email]', '$_POST[pseudo]')";
?>
What is the error ?
Thank you
Solution
You have not concatenated the $_POST[] variable correctly.
You have been missing the close brace for the mysqli_query opening.
It is advised to have a separate query and then to execute the mysqli_query().
Necessary Checks:
Ensure that you have given the name for the input type in the form attributes.
Have a check that whether you have called the name what you have given in the form at the PHP code while insert.
(E.g) - Input Attribute needs to be like this
<input type="email" name="email" value="" />
Like this you have to provide for all the Input types.
PHP Code
Usage of the mysqli::real_escape_string is better if you use it avoids SQL Injection.
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$email=mysqli_real_escape_string($con,$_POST['email']);
$pseudo=mysqli_real_escape_string($con,$_POST['pseudo']);
$stmt = "INSERT INTO posts (`email`, `pseudo`)VALUES('".$email."','".$pseudo."')";
$query = mysqli_query($con,$stmt);
if($query)
{
echo "Inserted Successfully";
}
else
{
// Handle Error over here.
}
?>
$email=$_POST['email'];
$pseudo=$_POST['pseudo'];
mysqli_query($connect,"INSERT INTO `posts` (`email`, `pseudo`) VALUES ('$email', '$pseudo');");
You have missed quote inside POST .Check below code
<?php
//Connecting to sql db.
$connect = mysqli_connect("","","","");
$sql ="INSERT INTO posts (email, pseudo)VALUES('".$_POST['email']."','".$_POST['pseudo']."')";
//Sending form data to sql db.
mysqli_query($connect,$sql);
?>
Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>
I am having some difficulties using the PHP insert into statement to add a new row to a MYSQL Table. I have granted all privileges to the remote user and I have been able to view to table fine. However, when I try to insert into the table I also get A NULL return. Any suggestions?
Here is the code:
<?php
$ID1=$_REQUEST["ID1"];
$ID2=$_REQUEST["ID2"];
$ID3=$_REQUEST["ID3"];
$ID4=$_REQUEST["ID4"];
$ID5=$_REQUEST["ID5"];
$return = "0";
$link = mysql_connect('my-remote-server', 'root', 'pwd');
if (!$link) {echo $return; $end ="1";}
$db_selected = mysql_select_db($ID3, $link);
if (!$db_selected) {echo $return; $end ="1";}
if ($end != "1")
{
if (($ID5 == "1") && ($ID4 == "%%%"))
{
$check = mysqli_query($link,"INSERT INTO Students (NetID, GroupID)
VALUES ('%s', '%s')",
mysql_real_escape_string($ID1),
mysql_real_escape_string($ID2));
echo var_dump($check);
echo "1";
}
}
Like we said in the initial comments, stick to a single extension: mysql or MySQLi. In this case, I would strongly advise MySQLi due to the deprecation of the mysql extension in PHP 5.3+.
Your code can be changed (and made more secure) by modifying it to:
<?php
$ID1=$_REQUEST["ID1"];
$ID2=$_REQUEST["ID2"];
$ID3=$_REQUEST["ID3"]; // database name apparently ?
$ID4=$_REQUEST["ID4"];
$ID5=$_REQUEST["ID5"];
$return = "0";
$db = new mysqli('my-remote-server', 'root', 'pwd', $ID3);
if($db) {
if (($ID5 == "1") && ($ID4 == "%%%")) {
$statement = $db->prepare("INSERT INTO Students (NetID, GroupID) VALUES (?, ?)"); // prepare the query, this prevents SQL injection
$statement->bind_param('ss', $ID1, $ID2); // this tells MySQLi that the 2 variables are strings and should be properly escaped to fit in the query (automatically)
$statement->execute(); // run the actual query
}
}