MySQLi not working using INSERT - php

When I submit the below it does not error out but it also does not insert the data into the table. I am a beginner in php so have mercy.
<?php
/* include_once 'dbconn.php';*/
include 'menu.php';
error_reporting(0);
?>
<head></head>
<body>
<form action="add_student.php" method="post">
Name:<input type="text" name="name"><br/>
School:<input type="text" name="school"><br/>
PR:<input type="text" name="pr"><br/>
<input type="submit" name="submit">
</form>
<?php
$DB_host = "localhost";
$DB_user = "root";
$DB_pass = "root";
$DB_name = "trackmeet";
$MySQLiconn = new MySQLi($DB_host,$DB_user,$DB_pass,$DB_name);
if($MySQLiconn->connect_errno)
{
die("ERROR : -> ".$MySQLiconn->connect_error);
}
if (isset($_POST['submit'])){
$sql = "INSERT INTO student(Student,School,PR) VALUES ('$_POST[name]','$_POST[school]','$_POST[pr])";
mysqli_query($sql,$MySQLiconn);
mysqli_close($MySQLiconn);
}
?>
</body>
</html>
When I look in the database table the record was not inserted.

I found the problem.
mysqli_query($sql,$MySQLiconn);
changed to
$sql = $MySQLiconn->query($sql);
Thanks for the help. Nice to have people out there that are willing to teach people like me.

You have typo missing this in query ' on value $_POST[pr]
original:
$sql = "INSERT INTO student(Student,School,PR) VALUES ('$_POST[name]','$_POST[school]','$_POST[pr])";
mysqli_query($sql,$MySQLiconn);
fixed:
$sql = "INSERT INTO student(Student,School,PR) VALUES ('$_POST[name]','$_POST[school]','$_POST[pr]')";
mysqli_query($sql,$MySQLiconn);

You have the order of your parameters wrong;
mysqli_query($sql,$MySQLiconn);
should be
mysqli_query($MySQLiconn,$sql);
or use the object orientated method if you so wish
$MySQLiconn->query($sql);

Related

Can't insert string (lettters) into mysql . Numbers work fine

So here I come with another problem. I can't push strings into mysql table. If I use numbers it works fine. If I try to insert text as value it works as well. No luck with text that was put in textboxes in html.
$current_user = wp_get_current_user();
$hostname = "XXX";
$username = "XXX";
$password = "XXX";
$dbname= "XXX";
$connect=mysqli_connect($hostname, $username, $password, $dbname);
$sql="insert into wypozyczenia (czy_wypozyczony, sn, model) values (2,"
.mysql_escape_string($_POST['SN']).",
".mysql_escape_string($_POST['model']).")";
if ($current_user->ID=2)
{
?><form name="form" method="post" >
Model:</br>
<input type="text" name="model"></br>
Numer Seryjny</br>
<input type="text" name="SN"></br>
<input type="submit" name="button1" value="Send">
</form>
<?php
if(isset($_POST["button1"])){
$model=$_Post["model"];
$SN=$_Post["SN"];
?> <pre><?php var_dump($_POST); ?></pre><?php
mysqli_query($connect,$sql);}}
Try adding single quote before the double quote, like the following:
$sql = "insert into wypozyczenia (czy_wypozyczony, sn, model) values (2,
'".mysql_escape_string($_POST['SN'])."',
'".mysql_escape_string($_POST['model'])."')";
You can use sprintf for beauty code or learning prepare statement in PHP PDO
$sql = sprintf("insert into wypozyczenia (czy_wypozyczony, sn, model) values (2,'%s','%s')"
,mysql_escape_string($_POST['SN'])
,mysql_escape_string($_POST['model']));

PHP code for a HTML form sending data to a MySQL database?

I have this form:
<form action="contactus.php" method="post">
<select name="formTitle">
<option value="">Select...</option>
<option value="M">Mr</option>
<option value="F">Mrs</option>
</select>
<p><b>Name</b></p>
<input type="text" name="formName" maxlength="50"/>
<p><b>Enquiry</b></p>
<input type="text" name="formEnquiry" maxlength="500"/>
</select>
<p><input type="submit" name="formSubmit" value="Submit"/></p>
And I have a MySQL database (called 'contacts') with a table (called 'enquiries') with three columns; 'Title', 'Name', 'Enquiry'.
The database has no password or anything. It's just a localhost with a 'root' password.
What kind of PHP would I need to send the data from this HTML form to the MySQL database?
I can help you in this problem.
So, just add the following code to your php file contactus.php.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "contacts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['formSubmit'])) {
$formTitle = $_POST['formTitle'];
$formName = $_POST['formName'];
$formEnquiry = $_POST['formEnquiry'];
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES ('$formTitle', '$formName', '$formEnquiry')";
$conn->query($sql);
?>
I hope this will solve your problem.
SIMPLE ANSWER: MySQL
A LITTLE BIT MORE DEVELOPED ANSWER:
MySQL is in basic terms the combination of PHP and SQL to create an easy way to do various actions to a database, which include:
Create table
Query table
Update table
and much more
There are variations of MySQL, including MySQLi and MySQL (PDO).
an example of connecting to your database via MySQL (PDO) would be:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$myDB = "databasename";
try {
$conn = new PDO("mysql:host=$servername;dbname=$myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
//insert code there that you want to execute...
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
you mentioned that you don't have a password, so you might just leave the "password" slot empty ("") I suppose, though this is very insecure and I recommend you place a password.
In the code above, there is a comment that says:
//insert code there that you want to execute...
Here you would include code that would probably do actions similar to the ones mentioned above (query table, update table, etc). An example of code similar to that would be:
//htmlspecialchars takes out special characters that might
//exist in the posted information if someone were trying
//to hack your site via sql injection
$formTitle = htmlspecialchars($_POST['formTitle']);
$formName = htmlspecialchars($_POST['formName']);
$formEnquiry = htmlspecialchars($_POST['formEnquiry']);
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES (formTitleBinded, formNameBinded, formEnquiryBinded)";
$sqlPrepared = $conn->prepare($sql);
$sqlPrepared->bindParam(':formTitleBinded',$formTitle);
$sqlPrepared->bindParam(':formNameBinded',$formName);
$sqlPrepared->bindParam('formEnquiryBinded',$formEnquiry);
$sqlPrepared->execute();
The previous code both sanitizes your input and inserts a row into your table with that information.
Let me know if that helped!
EDITED: My answer has been edited with parameter binding included to prevent SQL Injection.

Correction on Inserting data into SQL Table via PHP

I've been using php and mysql for my computing project and I've just run into this small problem. I've tried countless numbers of variations to this line of code but I always seem to receive an SQL Error.
Background Information:
HTML Document that contains a form, allowing the Admin to upload an image path, a name for the photo and a comment as well
PHP Document containing SQL that runs the code for this. I've worked out how to insert either an image path, a name or a comment but not all three at once...
Here's the line of code that causes the problem, specifically inserting the data into the database.
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('{$_POST{[ VALUES GO HERE, WHAT SYNTAX/HOW??? ]}')";
The HTML Form is here (for anyone interested):
<form action="insertTest.php" method="POST" enctype="multipart/form-data">
Image: <input type="text" name="image" /><br>
Name: <input type="text" name="name" /><br>
Comment: <input type="text" name="comment" /><br>
<input type="submit">
</form>
PHP Doc (whole upload file, quite small, changed password for security xD):
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "admin_db";
// Create connection
$conn = new mysqli($servername = "localhost", $username = "root", $password = "password", $dbname = "admin_db");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('{$_POST{[]}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
$image = $_POST['image'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('$image', '$name', '$comment')";
you can set variables to the associative array (with name from html form) and include each in the sql query. Something like this:
$image = $_POST['image'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql="INSERT INTO image_tbl (image, name, comment) VALUES ('$image','$name','$comment')";
Separate your variables $imgpath=$_POST["path"]; $imgname=$_POST["name"]; $imgcomment=$_POST["comment"]; now insert into table.... INSERT INTO imgtable(path,name,comment) VALUES('$imgpath','$imgname','$imgcomment')

return and add to database

I have tried to make the following code. I want to add date, day, fromtime, totime into my database. But when I choose the values in my forms, I dont get anything registred in my database. It is connected succesful to mysql.
The code is here:
<html>
<head>
</head>
<body>
<form method="post">
<h3>Add your worktime to database</h3><br>
<input type="date" name="date"><br><br>
<input type="text" name="day"><br>
<input type="time" name="fromtime">
<input type="time" name="totime">
<input type="submit" value="submit"><br><br>
</form>
</body>
<?php
$username = "root";
$password = "root";
$hostname = "127.0.0.1:3306";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br><br>";
//select a database to work with
$selected = mysql_select_db("danskebank",$dbhandle)
or die("Could not select examples");
$date = $_POST['date'];
$day = $_POST['day'];
$fromtime = $_POST['fromtime'];
$totime = $_POST['totime'];
$sql = "INSERT INTO addWorkTime(date, day, fromtime, totime) VALUES('$date', '$day', '$fromtime', 'totime')";
//execute the SQL query and return records
$result = mysql_query("SELECT date, day, fromtime, totime FROM addWorkTime");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
Print"<h3>Return from database:</h3>";
echo "Date: ".$row{'date'}."<br>"."Day: ".$row{'day'}."<br>"."From Time: ".$row{'fromtime'}."<br>"."To Time: ".$row{'totime'}; //display the results
}
?>
</html>
I hope somebody can help me?
Best Regards Mads
RoyalBG is correct, you need to have the line $result = mysql_query($sql); in your code at the correct point to actually run your insert line. Also you should read up on SQL Injection because your code as you've written it currently is extremely vulnerable to SQL Injection.

PHP not inserting into tables

I'm having trouble getting a practice signup form to submit data to my database ...
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$name = $email = $password = "";
?>
<form method="post">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Password: <input type="text" name="password">
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
function fix_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
In addition to Ugur's answer, you are mismatching mysqli commands and mysql commands. Here's how to do this in an object oriented fashion:
// create mysqli database object
$mysqli = new mysqli_connect("localhost","username","password","database");
// store your query in a variable. question marks are filled by variables
$sql = "INSERT INTO table_name ('username','password') VALUES (?,?)";
// prepare command uses $sql variable as query
$stmt = mysqli->prepare($sql);
// "ss" means your 2 variables are strings, then you pass your two variables.
$stmt->bind_param("ss",$name,md5($password));
// execute does as it seems, executes the query.
$stmt->execute();
// then print your success message here.
Using prepared statements removes the need to sanitize user input, as harmful input is not substituted into the query directly. For more reading:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
There are some good tips for using prepared statements in many different scenarios, as well as towards the bottom, there is an explanation on how prepared statements prevent SQL injection.
Missing table name
mysql_query("INSERT INTO ...... ('username','password') VALUES ('$name', md5('$password'))");
You're mixing mysql_* with mysqli_* functions, i.e.: mysqli_connect and mysql_query and you're wrapping your column names in quotes, plus you're missing the table name to insert into.
Try the following, fixed code:
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysqli_query("INSERT INTO `your_table` (`username`,`password`) VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
You're also using password storage technology that dates back to 1996. MD5 is no longer considered safe to use.
I suggest you look into PHP's password function: http://php.net/password
And if you're having problems with your fix_input() function, you should consider using the mysqli_real_escape_string() function.
then setting up a DB connection while passing a variable to it.
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
and instead of using:
$name = fix_input($_POST["name"]);
use the following:
$name= mysqli_real_escape_string($db, $_POST['name']);
and do the same for the rest.
you don't have table name in your query! also do not use quotation in your column name :)
you have mixed up mysqli and mysql.
Change
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
to
mysqli_query("INSERT INTO yoour_table(username',password) VALUES ('$name', md5('$password'))");

Categories