Inserting form data to a mysql database - php

I have tried multiple times to get this code to run and insert the data into a my database. No matter what I try I cannot figure out the problem. The php looks like this:
<?php
// Create connection
$conn = mysqli_connect("localhost","nmhsmusi_admin" , "********", "nmhsmusi_musicdb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['submit']))
{
$titleTag = $_POST['title'];
$composerTag = $_POST['composer'];
$unicodeTag = $_POST['unicode'];
$tempoTag = $_POST['tempo'];
$yearTag = $_POST['year-used'];
$languageTag = $_POST['language'];
$keyTag = $_POST['key-signature'];
$pianoTag = $_POST['piano'];
$temposelTag = $_POST['temposel'];
$partsTag = $_POST['parts'];
$run = mysqli_query($conn,"INSERT INTO musicdb (title, composer, unicode, temptxt, yearused, languages, pianokeys, piano, temposel, parts)
VALUES
(
'$titleTag', '$composerTag', '$unicodeTag', '$tempoTag', '$yearTag', '$languageTag', '$keyTag', '$pianoTag', '$temposelTag', '$partsTag'
)");
if ($run) {
echo "New record created successfully";
} else {
echo "failed";
}
mysqli_close($conn);
}
?>
Any help would be greatly appreciated

Why do you use mysqli? Has it already fallen into disuse?
PDO is now used.
Here's an example:
<?php
if (isset($_POST['submit'])) {
$titleTag = $_POST['title'];
$composerTag = $_POST['composer'];
$unicodeTag = $_POST['unicode'];
$tempoTag = $_POST['tempo'];
$yearTag = $_POST['year-used'];
$languageTag = $_POST['language'];
$keyTag = $_POST['key-signature'];
$pianoTag = $_POST['piano'];
$temposelTag = $_POST['temposel'];
$partsTag = $_POST['parts'];
try {
$pdo = new PDO(DSN,DBUSER,DBUSERPASSWD);
} catch (PDOException $e) {
echo "Failed to connect to Database: " . $e->getMessage() . "\n"; die();
}
$pdo->exec("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
$sql = "INSERT INTO musicdb (title, composer, unicode, temptxt, yearused, languages, pianokeys, piano, temposel, parts)
VALUES (:titleTag,:composerTag,:unicodeTag,:tempoTag,:yearTag,:languageTag,:keyTag,:pianoTag,:temposelTag,:partsTag)";
$query = $pdo->prepare("$sql");
$query->bindValue(':titleTag',$titleTag);
$query->bindValue(':composerTag',$composerTag);
$query->bindValue(':unicodeTag',$unicodeTag);
$query->bindValue(':tempoTag',$tempoTag);
$query->bindValue(':yearTag',$yearTag);
$query->bindValue(':languageTag',$languageTag);
$query->bindValue(':keyTag',$keyTag);
$query->bindValue(':pianoTag',$pianoTag);
$query->bindValue(':temposelTag',$temposelTag);
$query->bindValue(':partsTag',$partsTag);
$query->execute();
if($query->rowCount() > 0){
echo "New record created successfully!";
} else {
echo "Error!";
}
}
?>
Of course you need to filter everything that comes from the form with regular expressions. Easy thing to do!
Once the regular expressions have analyzed everything you need to convert everything to htmlentities to avoid malicious code:
The regular expression "/([a-zÀ-ÿ0-9\s]+)/i" below allows only letters with or without accents, numbers, and spaces:
<?php
preg_match('/([a-zÀ-ÿ0-9\s]+)/i', $_POST['any_field_form'], $output);
if((isset($output[1]) == true) and ($output[1] != null)) {
//Convert everything to htmlentities to avoid malicious code
$get_the_data = htmlentities($output[1], ENT_QUOTES, 'UTF-8', false);
} else {
$get_the_data = null;
}
?>
With this you avoid problems with forms. Of course for each form field you will have to do a specific regular expression. But that makes your code smarter.
Sorry if there are any errors in the text. I know how to read in English, but I do not know how to write so I used a translator for that.
But that's it, boy!

Related

Error adding data in mysql table using PHP

I'm making a simple CURD operation using PHP and MYSQL. However I'm not able to insert/add data in the created table.
I think it might be a syntax error itself, but I can't figure out which one. The rest of the code works fine.
operation.php:
require_once("../CRUD/php/db.php");
$conn = createDB();
if(isset($_POST['create']))
{
createData();
}
function createData()
{
$name = textboxValue("name_type");
$age = textboxValue("age_type");
$gender = textboxValue("gender_type");
$email = textboxValue("email_type");
$contact = textboxValue("contact_type");
$dept = textboxValue("dept_type");
$sql = "INSERT INTO details(name,age,gender,email,contact,department)
VALUES('$name', '$age', '$gender', $email', '$contact', '$dept');";
if(mysqli_query($GLOBALS['conn'],$sql))
{
echo "Data added";
}
else
{
echo "Error adding data";
}
}
function textboxValue($value)
{
$textbox = mysqli_real_escape_string($GLOBALS['conn'], trim($_POST[$value]));
if(empty($textbox))
{
return false;
}
else
{
return $textbox;
}
}
"Error adding data" gets echoed. I can share the html code as well if needed.
$sql = "INSERT INTO details(name,age,gender,email,contact,department)
VALUES(\"$name\", \"$age\", \"$gender\", \"$email\", \"$contact\", \"$dept\");";
and so? By the way one quote you forgot near $email

MySQL INSERT in PHP no error feedback

I am trying to input data to MySQL using PHP. Don't know what's wrong. The connection succeeds, no errors but at the end there is not data being written to the database.
$dbhost = "localhost";
$dbname = "listings";
$un = $_POST["un"];
$pass = $_POST["pass"];
$name = $_POST["name"];
$des = $_POST["des"];
$quan = $_POST["quantity"];
$specs = $_POST["specs"];
$price = $_POST["price"];
$url1 = ".";
$url2 = ".";
$url3 = ".";
$url4 = ".";
$connection = mysqli_connect($dbhost,$un,$pass,$dbname);
if (!$connection) {
die("Error".mysqli_error);
} else {
echo "Database connection successfull ".$des;
}
$query = "INSERT INTO items
(name,description,quantity,specs,price,url1,url2,url3,url4) VALUES
'$name','$des','$quan','$specs','$price','$url1','$url2','$url3','$url4')
";
echo "Hellos";
$exeute_query = mysqli_query($query,$connection);
if(!execute_query){
die("error ".mysqli_error());
echo "query error";
} else {
echo "Query successfull";
}
mysqli_close($connection);
Any help?
There are several small mistakes in your code:
$query = "INSERT INTO items (name,description,quantity,specs,price,url1,url2,url3,url4) VALUES ('$name','$des','$quan','$specs','$price','$url1','$url2','$url3','$url4')";
echo "Hellos";
**$exeute_query** = mysqli_query($query,$connection); // $execute_query instead of $exeute_query
if(!**execute_query**){ //$execute_query instead of execute_query
die("error ".mysqli_error());
echo "query error";
}
else{echo "Query successfull";}
mysqli_close($connection);
?>
Your code breaks at the if statement because no fucntion with that name is found (if you do not use the dollarsign to show it is a variable, php will interpret it as a function. Also, when initiating your variable you forgot a 'c' so make sure to check if you have the correct variable name or php won't find your variable. Now your query will work or give an error message in case of wrong data formats or bad connection. Use code listed below to debug your php in the future.
error_reporting(E_ALL);
ini_set('display_errors', 'On');

Not able to insert the data from url to database in php

final.php
Here I am trying to get the data from the url using GET method and trying to insert into the database. I was able to insert the data for first few rows after that the data is not inserted. Can anyone help me regarding this?
when I try to run the url: www.myii.com/app/final.php?name=123&glucose=3232...
the data is not inserting.
<?php
include("query_connect.php");
$name = $_GET['name'];
$glucose = $_GET['glucose'];
$temp = $_GET['temp'];
$battery = $_GET['battery'];
$tgs_a = $_GET['tgs_a'];
$tgs_g = $_GET['tgs_g'];
$heartrate = $_GET['heartrate'];
$spo2 = $_GET['spo2'];
$rr = $_GET['rr'];
$hb = $_GET['hb'];
$ina22 = $_GET['ina22'];
$accucheck = $_GET['accucheck'];
$isactive = $_GET['isactive'];
$address = $_GET['address'];
$deviceno = $_GET['deviceno'];
$sql_insert = "insert into query (name,glucose,temp,battery,tgs_a,tgs_g,heartrate,spo2,rr,hb,ina22,accucheck,isactive,address,deviceno) values ('$name','$glucose','$temp',$battery','$tgs_a','$tgs_g','$heartrate','$spo2','$rr','$hb','$ina22','$accucheck','$isactive','$address','$deviceno')";
mysqli_query($sql_insert);
if($sql_insert)
{
echo "Saving succeed";
//echo $date_time;
}
else{
echo "Error occured";
}
?>
Query_connect.php
This is my database config php file.
<?php
$user = "m33root";
$password = "me3i434";
$host = "localhost";
$connection = mysqli_connect($host,$user,$password);
$select = mysqli_select_db('miiyy',$connection);
if($connection)
{
echo "connection succesfull<br>";
}
else {
echo "Error";
}
?>
Make sure that all columns can contain NULL so that not filled fields will stay NULL instead of throwing an error.
Try below to see mysql error:
mysql_query($sql_insert);
echo mysql_error()
Try these
In SQL
Change the table name of query to some other name. Because "query" is reserved in SQL
In code
if (!mysqli_query($con,$sql_insert ))
{
echo("Error description: " . mysqli_error($con));
}
else
{
echo "Success";
}
Use mysqli_error() function

Can't record fields into database (php, SQL)

I'm trying to take a form that a user inputs from an HTML site and send the information to a SQL database. I am able to print out the variables after submission, so I know at the very least the variables are set properly. So I have to assume my code to send the content to the database is at fault here.
Here's the code:
//Taking variables from HTML input
if (isset($_POST['group'])) {
$group = $_POST['group'];
} else {
echo $error; return;
}
if (isset($_POST['game'])) {
$game = $_POST['game'];
} else {
echo $error; return;
}
if (isset($_POST['platform'])) {
$platform = $_POST['platform'];
} else {
echo $error; return;
}
if (isset($_POST['player'])) {
$player = $_POST['player'];
} else {
echo $error; return;
}
if (isset($_POST['play'])) {
$play = $_POST['play'];
} else {
echo $error; return;
}
if (isset($_POST['timezone'])) {
$timezone = $_POST['timezone'];
} else {
echo $error; return;
}
$error = 0;
//Retrieving Databse
try {
//userID and password is defined, just hiding it here
$dbh = new PDO("mysql:host=localhost;dbname=userID", "userID", "password");
} catch (Exception $ex) {
die("<p>($e->getMessage())</p></body></html>)");
}
//Inputting content into MySQL
$command = "INSERT INTO teams ( group, game, platform, player, play, timezone )
VALUES ( '$group','$game','$platform','$player','$play','$timezone')";
$stmt = $dbh -> prepare($command);
if ( ! $stmt->execute() ) {
$error = "<b>ERROR:</b> Could not record fields"; echo $error; return;
}
I'm not really sure where I've gone wrong, could be possible it's the tiniest thing or just something I've overlooked.
Thanks in advance for any help, guys!
This is how I did it for my Assignment:
Connecting to MySQL (notice that I dont have any mysql:host=):
$mysqli = new mysqli("localhost", "username", "pass", "database_name");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
Then in your code, when initializing variabels from POST, escape the strings. This will give you some protection against SQL-Injections:
$Name = $mysqli->real_escape_string($_POST["txtName"]);
$Street = $mysqli->real_escape_string($_POST["txtStreet"]);
$City = $mysqli->real_escape_string($_POST["txtCity"]);
Now, prepare a SQL code to insert your params:
$input = $mysqli->query("INSERT INTO customer (MembershipID, Name, Street, City, PostCode, Email, Password, DateJoin, Salt)
VALUES ('". $MembershipID."','".$Name."','".$Street."','". $City."','". $PostCode."','". $Email."','". $Password."','". $DateJoined."','". $Salt."')");
I hope it helps, Good Luck.

Update query not working using PDO

I tried updating my data like so but it doesn't work
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(!empty($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$query_params = array(':shell' => $_POST['shell'], ':reporter' => $_POST['reporter']);//Updates likes
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
the config.inc.php
<?php
// These variables define the connection information for your MySQL database
$username = "xmnj3jh0jhtheu_14265914";
$password = "jhikjskjiavethew";
$host = "sqlkjnlkkjlk101.x3kuhiu0lkj.us";
$dbname = "x3lnklj0u_1426jbkb5914_gbabbjkhjajhlert";
// UTF-8 is a character encoding scheme that allows you to conveniently store
// a wide varienty of special characters, like � or �, in your database.
// By passing the following $options array to the database connection code we
// are telling the MySQL server that we want to communicate with it using UTF-8
// See Wikipedia for more information on UTF-8:
// http://en.wikipedia.org/wiki/UTF-8
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// A try/catch statement is a common method of error handling in object oriented code.
// First, PHP executes the code within the try block. If at any time it encounters an
// error while executing that code, it stops immediately and jumps down to the
// catch block. For more detailed information on exceptions and try/catch blocks:
// http://us2.php.net/manual/en/language.exceptions.php
try
{
// This statement opens a connection to your database using the PDO library
// PDO is designed to provide a flexible interface between PHP and many
// different types of database servers. For more information on PDO:
// http://us2.php.net/manual/en/class.pdo.php
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
// If an error occurs while opening a connection to your database, it will
// be trapped here. The script will output an error and stop executing.
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code
// (like your database username and password).
die("Failed to connect to the database: " . $ex->getMessage());
}
// This statement configures PDO to throw an exception when it encounters
// an error. This allows us to use try/catch blocks to trap database errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This statement configures PDO to return database rows from your database using an associative
// array. This means the array will have string indexes, where the string value
// represents the name of the column in your database.
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// This block of code is used to undo magic quotes. Magic quotes are a terrible
// feature that was removed from PHP as of PHP 5.4. However, older installations
// of PHP may still have magic quotes enabled and this code is necessary to
// prevent them from causing problems. For more information on magic quotes:
// http://php.net/manual/en/security.magicquotes.php
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
// This tells the web browser that your content is encoded using UTF-8
// and that it should submit content back to you using UTF-8
header('Content-Type: text/html; charset=utf-8');
// This initializes a session. Sessions are used to store information about
// a visitor from one web page visit to the next. Unlike a cookie, the information is
// stored on the server-side and cannot be modified by the visitor. However,
// note that in most cases sessions do still use cookies and require the visitor
// to have cookies enabled. For more information about sessions:
// http://us.php.net/manual/en/book.session.php
session_start();
// Note that it is a good practice to NOT end your PHP files with a closing PHP tag.
// This prevents trailing newlines on the file from being included in your output,
// which can cause problems with redirecting users.
?>
don't know what's wrong and it gives no error it goes into the else statement, meaning the values were not updated. i tried the same code in sqlfiddle and it works but not in my PhpMyAdmin.
I know the updated value is supposed to be passed into the $query_params but am incrementing the value of likes each time it is run, and am not sure how to do that in the $query_params unless i use a seperate query to get the numberof likes and then increament it but that could be costly.
Query without PDO still it does not work this time it give update unsuccessful
<?php
$username = "x3jbhiukhkj0u426jbhjnbvh591mbhb4";
$password = "savjiuejbiuhilkmthljiew";
$host = "sqlnjhbjhnkjjjhbj";
$dbname = "x3hjbh0ukjioiuhgbjhvhgvh";
$shell = "Rustig";
$reporter = "davies";
//query
$query = "UPDATE `shellingdb`
SET `favs` = 1
WHERE `shell` = 'Rustig'";
$link = mysql_connect($host, $username, $password);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}else
{
echo 'Connected successfully';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected)
{
die ('Can\'t use foo : ' . mysql_error());
}else
{
echo 'Connected to database successfully';
if(empty($_POST))
{
$retval = mysql_query( $query, $link )or die(mysql_error($link));;
if(! $retval )
{
die('Could not query database: ' . mysql_error());
}else
{
if(mysql_affected_rows() > 0)
{
echo "Updated data successfully\n";
}else
{
//echo "shell=".$shell." reporter=".$reporter';
echo "Updated data Unsuccessfully\n";
}
}
}
}
}
mysql_close($link);
?>
The below is the output of the PDOStatement::debugDumpParams(); for the first php syntax
SQL: [124] UPDATE shellingdb SET likes = likes + 1 WHERE shell = :shell AND reporter >= :reporter Params: 2 Key: Name: [6] :shell paramno=-1 name=[6] ":shell" is_param=1 param_type=2 Key: Name: [9] :reporter paramno=-1 name=[9] ":reporter" is_param=1 param_type=2
I used bindParam. bindParam is a method on PDOStatement.
Try:
<?php
require("config.inc.php");//this piece of code us for authentication and it works fine.
if(isset($_POST))
{
/**
the values below in the POST are valid not empty values
**/
$shell = $_POST['shell'];
$reporter = $_POST['reporter'];
//query
$query = "UPDATE `shellingdb`
SET `likes` = `likes` + 1
WHERE `shell` = :shell AND `reporter` = :reporter";
try {
$stmt = $db->prepare($query);
$stmt->bindParam(":shell", $shell);
$stmt->bindParam(":reporter", $reporter);
$stmt->execute();
$affected = $stmt->rowCount();//counts the number of affected rows during the update query
if($affected > 0)
{
$response["success"] = 1;
$response["message"] = "Updated! this number of rows were affected".$affected;
echo json_encode($response);
}else
{
$response["success"] = 2;
$response["message"] = "Not Updated! huh!".$affected;
echo json_encode($response);
}
}
catch (Exception $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!".$ex->getMessage();
die(json_encode($response));
}
}
?>
some how, after long hours of try and error(Brut Forcing) this finally worked
$query = "UPDATE `shellingdb` SET `likes`=`likes`+1 WHERE `shell` = :shell AND `reporter` = :reporter";
Thanks all those who tried to help. :)

Categories