No data inserted into mssql database using php - php

I would like to insert data from a form using php into mssql 2012.
The above picture shows I installed drivers for php to work with mssql and after testing the connection it was success.
Following is the script written to do the insertion:
$serverName = "SUPERMAN";
$connectionInfo = array('Database'=>'xikwambene', "UID"=>"develop", "PWD"=>"develop");
$conn = sqlsrv_connect($serverName, $connectionInfo);
if($conn) {
echo "Connection established.<br />";
}else {
echo "Connection could not be established.<br />";
die(print_r(sqlsrv_errors(), true));
}
if(empty($_POST) === false && empty($errors)=== true)
{
$id = $_POST['id'];
$name = $_POST['name'];
$query = "INSERT INTO dbo.test (id,name)
VALUES ('$id','$name')GO";
$result = sqlsrv_prepare($conn,$query)or die('Error querying MSSQL database');
sqlsrv_execute($result);
//redirect
header('Location: Address_insert.php');
exit();
}
?>
Now the problem is nothing gets inserted into the database, and it successfully redirects to
Address_insert.php
Please Assist. its my first day working with php and mssql

if(empty($_POST) === false && empty($errors)=== true)
{
$id = $_POST['id'];
$name = $_POST['name'];
print_r($_POST);
$query = "INSERT INTO dbo.test (id,name)
VALUES (?,?)";
$params = array($id, $name);
$stmt = sqlsrv_query( $conn, $query, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
The answer is based on information from: http://www.php.net/manual/en/function.sqlsrv-query.php

After this code:
$id = $_POST['id'];
$name = $_POST['name'];
add this :
$id = $_POST['id'];
$name = $_POST['name'];
print_r($_POST)
to see if the script receive the php variables sent thru $_POST and comment :
//header('Location: Address_insert.php'); so you can see the print.
This method for me always give results.
Best regards!

$query = "INSERT INTO dbo.test (id,name)
VALUES ('$id','$name')GO";
$result = sqlsrv_prepare($conn,$query)or die('Error querying MSSQL database');
Here, $query is not compatible for a prepared statement. You don't assign parameters in queries in prepared statements, you use place holders like ?. If you wish to use prepared statements, you are doing it in a wrong way. If you wish to use regular queries, you would want to remove the sqlsrv_prepare ( ) line of code.

Related

I am trying to add some data in database using PHP, but it does not work

This is my PHP code starting and used connection type is PDO.
//connection with server
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=gujaratoil", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['submit']))
{
//at the beginning null value is set
$name = $emailaddress="";
$sql = "INSERT INTO
registration(name,emailaddress)VALUES('$_POST[name]','$_POST[emailaddre
ss]')";
}
?>
I have tried all the solutions available; what should I do to solve this issue? I am using a PDO connection.
When using PDO you should use prepared statements rather than directly embedding variables in the SQL.
The reason, I believe, given the code above why the insert was failing was / is due to the lack of quotes around field names within $_POST[] ~ ie $_POST[name] which is likely to be causing undeclared constant errors
$name=$_POST['name'];
$email=$_POSt['emailaddress'];
$sql='insert into `registration` ( `name`, `emailaddress` ) values ( :name, :email )';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$stmt->bindParam(':name',$name);
$stmt->bindParam(':email',$email);
$stmt->execute();
}

SQL insert to MySQL doesn't work

I'm currently trying to insert username, pw to a DB, and check if the username already exists.
The problem is that the SQL (select) syntax doesn't work, nor does the (insert). I've checked around for a couple of hours in forums and Stackoverflow, and my current code is the following.
What might be the problem?
Thanks, Jimmie.
<?php
$servername = "localhost";
$username = "name";
$password = "pw";
$dbname = "dbaname";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ((isset ($_POST["identity"])) && (isset ($_POST["pin"])) && (isset ($_POST["token"])))
{
$identity = htmlspecialchars($_POST['identity'], ENT_QUOTES, "ISO-8859-1");
$pin = htmlspecialchars($_POST['pin'], ENT_QUOTES, "ISO-8859-1");
$token = htmlspecialchars($_POST['token'], ENT_QUOTES, "ISO-8859-1");
echo "$identity";
if($token == "xyz13D;A##:!#")
{
$result = $mysqli->query("SELECT `identity` FROM Users WHERE `identity` = '" . $identity . "'");
if($result->num_rows == 0)
{
echo "successCreat";
// Perform queries
mysqli_query($mysqli,"SELECT * FROM Users");
mysqli_query($mysqli,"INSERT INTO Users (identity,pin,userActivity, identityCreated) VALUES ('$identity', '$pin',1,now())");
}
else
{
echo "failureCreate";
}
}
else
{
echo"Wrong Key";
}
}
$mysqli->close();
?>
Assuming that identity is a primary key, then you can check the error flags after executing an INSERT query to see if an error occurred.
mysqli_query( $mysqli, "INSERT INTO ... " ); //< ... Represents query
if (mysqli_error( $mysqli )) {
echo "Failure";
}
else {
echo "Success";
}
Also, you should properly escape input as stated in the comments. In addition, you should check whether or not the connection attempt was successful using mysqli_connect_error.
Finally, there might be an issue in your SQL suntax which mysqli_error will also catch. A last possibility is that the POST data isn't being set properly and the code is being ignored completely.

not response for database

This is the code for database connection in php:
<?php
$connection = mysql_connect("localhost", "root", "root"); // Establishing Connection with Server
$db = mysql_select_db("fimos", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$gender = $_POST["gender"]; //declare gender
$race = $_POST["race"];
$ic = $_POST["icno"];
$name = $_POST["name"];
$old_ic = $_POST["oldic"];
$add1 = $_POST["add1"];
$add2 = $_POST["add2"];
$add3 = $_POST["add3"];
$postcode = $_POST["postco"];
$town = $_POST["tow"];
$state = $_POST["state"];
$home_con = $_POST["homep"];
$fax_contact = $_POST["fax"];
$hp_con1 = $_POST["mobi1"];
$hp_con2 = $_POST["mobi2"];
$email = $_POST["email"];
if($ic !=''||$email !=''){
//Insert Query of SQL
$query = mysql_query("INSERT INTO customer_info(cust_gender, cust_race, cust_ic,
cust_name, cust_old_ic, cust_add1, cust_add2, cust_add3, cust_postcode,
cust_town, cust_state, cust_home_con, cust_fax_contact, cust_hp_contact1,
cust_hp_contact2, cust_email)
VALUES ('$gender', '$race', '$ic' , '$name', '$old_ic', '$add1', '$add2',
'$add3', '$postcode', '$town', '$state', '$home_con', '$fax_contact',
'$hp_con1', '$hp_con2', '$email')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
Hi guys, I want to ask about the database connection, is it my code wrong somewhere?
Because I cant found any error in the code.
I click button register should come over this page to store the data.
when I come to this page display all blank.
I try to change the database name also no response.
I hope you guys can help me.
Thanks.
It should be:
$connection = mysql_connect("localhost", "root", ""); //empty the third parameter. If you have password then insert that in your third parameter
Paste this code inside your if condition so that it will return error from your sql query.
if (!$query) {
die('Invalid query: ' . mysql_error());
}
Try to use the PDO extension instead of mysql & mysqli function. The mysql_* functions are no longer maintained and community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi there are lots of benefits of using PDO over mysqli.
Add the above code
if($ic !=''||$email !=''){
$query = mysql_query("your query");
if (!$query) {
die('Invalid query: ' . mysql_error());
} else {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
}

Database does not respond Azure Microsoft

I've been programming this server / database in Microsoft Azure. And I've created this PHP to control everything. The main goal is to create a website where you are able to register and log in, for this I need a database and server which handles all these values.
In my code hoewever, the database doesn't seem to be storing anything, everything does what's expected, expect for the connection between database and PHP document. Therefore I turned to you guys, heard u'd be the best haha!
Just FYI, first post, be nice :)
Here's my PHP doc.
<?php
if (isset($_POST['submits']))
{
if (empty($_POST['usernames']))
{
$error = "Fill in all the boxes";
}
elseif (empty($_POST['passwords']))
{
$error = "Fill in all the boxes";
}
elseif (empty($_POST['emails']))
{
$error = "Fill in all the boxes";
}
elseif(strpos($_POST['emails'], "#") === false)
{
$error = "Wrong syntax: example#.com";
}
else
{
$username=$_POST['usernames'];
$password=$_POST['passwords'];
$email=$_POST['emails'];
$connectionInfo = array("UID" => "MY_SERVER_EMAIL", "pwd" => " MY_PASSWORD", "Database" => "MY_DATABASE", "LoginTimeout" => 30, "Encrypt" => 1);
$serverName = "(MY_DATABASE";
$conn = sqlsrv_connect($serverName, $connectionInfo);
$sql = "SELECT username, email FROM dbo.Login";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
$usertrue=TRUE;
if($usertrue===TRUE)
{
$error = "Account added";
$hashedpassword = md5(md5(sha1(sha1(md5($password)))));
$query = "INSERT INTO dbo.Login (username, password, email) VALUES ('$username', '$hashedpassword', '$email' )";
$result = sqlsrv_query($conn, $query );
if($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected succesfully";
}
sqlsrv_free_stmt( $stmt);
sqlsrv_close($conn); // Closing Connection
}
}
?>
The form is named POST and the inputs are named usernames, passwords, emails and submits.
Grateful for answers!
Anton
Looking at the code, I am assuming that you have replace the values with some place-holder.
Nevertheless, there might be some typo. There $ServerName has a "(". and I believe the Insert statement is not formatted correctly (i.e., all $username, $password, $email) is not getting evaluated because it is treated as string.
Also, why are you checking for connection error after executing the insert query. It should be checked first and re-connected if it is not connected before executing the insert query.

update user details, sql server 2008 sqlsrv

Hello i am having some trouble getting a script to run, i keep getting an error message saying it expects two parameters and i have no idea how to fix it, heres the script:
<?php
session_start ();
if(isset($_SESSION['user'])){
$username = $_SESSION['username'];
if(isset($_POST['submit'])){
$oldpassword = $_POST['oldpassword'];
$newpassword = $_POST['newpassword'];
$serverName = "server";
$connectionInfo = array("Database"=>"database","UID"=>"id", "PWD"=>"pass");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false){
echo "Error in connection.\n";
die( print_r( sqlsrv_errors(), true));
}
$tsql = "SELECT userPass FROM customers WHERE userName='$username'";
$stmt = sqlsrv_query($conn, $tsql, array(), array( "Scrollable" => 'static' ));
if ( !$stmt ){
die( print_r( sqlsrv_errors(), true));
}
$rows = sqlsrv_num_rows($stmt);
if($rows === false){
die( print_r( sqlsrv_errors(), true));
}elseif($rows == 0){
echo "No rows returned.";
exit();
}else{
$querychange = sqlsrv_query("UPDATE customers SET userPass='$newpassword' WHERE userName='$username'");
session_destroy();
die ("Your password has been changed. <a href='index.php'>Return</a> to the main page and login with your new password.");
}
}
}
?>
I keep getting this error
PHP Warning: sqlsrv_query() expects at least 2 parameters, 1 given in file_name.php on line 27
Line 27 is where i update customers. If anyone can spot an error in the script can you let me know, also yes I've not done SQL injection, at this stage I'm simply trying to get it working before I implement that.
Thanks for all the help, it's much appreciated
Try passing connection to sqlsrv_query
something like:
$querychange = sqlsrv_query($conn, "UPDATE customers SET userPass='$newpassword' WHERE userName='$username'");

Categories