Insert Data into MSSQL DB using PHP - php

Hello there am trying to insert data into MSSQL using PHP. I have tried many times to figure out what the problem might be but i seem not to find it. Is there something am not getting right or missing?
<?php
//pull form fields into php variables
$no = $_POST['no'];
$name= $_POST['name'];
$date = $_POST['date'];
$leave = $_POST['leave'];
$days= $_POST['days'];
$empno= $_POST['empno'];
//connect to sql
$dbc = mssql_connect('Server-PC','user','password','database')or die('Error connecting to
the SQL Server database.');
// Input into staff database
$query = "INSERT INTO dbo.[CAGD$Leave Plan] ([No_],[Employee No_],[Employee Name],
[Leave Name], [Start Date],[Leave Days],Satus) VALUES
('$no','$name','$leave','$date','days','empno')";
$r esult = mssql_query($query,$dbc)or die('Error querying MSSQL database');
//close to sql
mssql_close($dbc);
echo $name . 'Your submission has been received<br />';
echo 'If you need change this request please contact your HR Manager<br />';
echo 'Thank you <br />';
echo 'HR Manager';
?>
I get this error message:
Warning: mssql_query() [function.mssql-query]: message: Invalid object name 'dbo.CAGD Plan'.
(severity 16) in C:\xampp\htdocs\CAGD\leave_request.php on line 110
Warning: mssql_query() [function.mssql-query]: Query failed in C:\xampp\htdocs
\CAGD\leave_request.php on line 110
Error querying MSSQL database

You can use SQLSRV Driver instead of MSSQL Driver and then try this
<?php
$serverName = "serverName";
$options = array( "UID" => "sa", "PWD" => "Password", "Database" => "DBname");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$no = $_POST['no'];
$name= $_POST['name'];
$query = "INSERT INTO dbo.Test
(No_,FirstName)
VALUES(?, ?)";
$params1 = array($no,$name);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
This is more useful, and you can learn more here:
https://msdn.microsoft.com/en-us/library/cc626305(v=sql.105).aspx

First Specify your database Connection...
mssql_connect('Server-PC','user','password','database')
like -> "localhost","root","XXXX", "DBNAME"
then query like
$query = "INSERT INTO TABLENAME (id,name) VALUES
('$id','$name')";
$result = mssql_query($query,$dbc)

Hmm, it seems to me that you have 7 fields in the table but only 6 values submitted - you are missing the value for the first column, [No_].
Besides, the last column satus (i suppose it should be 'status') does not have de [] delimiters.
The error returned tells you that the name of the table is wrong.
And yes variable names are case sensitive in PHP, it should be $leave - best to exit the string and concatenate - something like "bla bla".$leave."anything here with spaces or not" .

Is this supposed to be a variable?
$query = "INSERT INTO dbo.[CAGD$Leave Plan] ([No_],[Employee No
^^^^^^
If so, then it's apparently undefined in your code, and the generated query string will contain dbo.[CAGD Plan], and not whatever value was supposed to be in that variable. If the $ is literally in your table name, then it should be CAGD\$Leave, so that $Leave isn't treated as a variable.

Related

PHP 7.1 query for User check gives out a Warning: A non-numeric value encountered in E:\XAMPP\htdocs

I'm facing a weird problem, I'm trying to implement a simple Usercheck with PHP 7.1.
$con = getConnection();
//check connection
if(!$con){
die("Connection to database failed". mysql_connect_error() );
} else echo ("connection to database successfull");
//checking if nickname already exists
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" + $nickname+ "'";
//sending query to sql database
$doesExist = mysqli_query($con, $checkUserExistanceSql)
or die ("Fehler in der Datenbankabfrage");
if(mysqli_num_rows($doesExist)>=1){
echo "Nickname not available, use another name";
}
But I'm getting this warning
Warning: A non-numeric value encountered in E:\XAMPP\htdocs... Line 29
Line 29 is the $checkUserExistanceSql. Any ideas where the problem is?
String concatenation on PHP uses . (dot) as operator, not + (plus).
You actual code uses +:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" + $nickname+ "'";
This is why PHP is telling that $nickname isn't a numeric variable. It cannot sum strings, only concatenate.
Change your operator to . and it will work:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" . $nickname . "'";
You can also use this syntax, with the same result but cleaner code:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='{$nickname}'";
Security Alert
You code is sucessive to SQL injection. You should use prepared statements instead of concatenating your variables into the Query.
Thanks to the help of Yolo and Elias Soares.
The script runs flawless now, I also used prepared statement to counter the risk of sql injection as mentiones by elias.
$con = getConnection();
//check connection
if(!$con){
die("Connection to database failed". mysql_connect_error() );
} else echo ("connection to database successfull");
//prepared statement for sql query
$stmt = $con -> prepare("SELECT nickname FROM user WHERE (nickname=?)");
$stmt -> bind_param("s", $nickname);
$stmt->execute();
//checkking result, if nickname is already used
if($stmt->get_result()){
echo "0";
} else {
//insert user
}

PHP/MySQL - Cannot get PHP script to put data into MySQL Database

I've spent most of the day trying to get data from a form into a MySQL Database, everything I have tried so far has not worked, can anyone figure out what is wrong? The database is connecting fine, it just cannot add any data into the mysql database (current errors are at the bottom)
EDIT: Updated Code Below (Still not working!)
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "report"; // Database name
$tbl_name = "tbl_nonconformance"; // Table name
// Connect to server and select database.
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
echo "Database Connected ";
$name = $_POST['name'];
$email = $_POST['email'];
$supplier = $_POST['supplier'];
$PONum = $_POST['PONum'];
$Part = $_POST['Part'];
$Serial = $_POST['Serial'];
$tsf = $_POST['tsf'];
$Quantity = $_POST['Quantity'];
$probclass = $_POST['probclass'];
$desc = $_POST['desc'];
$sql="INSERT INTO tbl_nonconformance (sno, Date, Name, Email, Supplier, PONum, Part, Serial, TSF, Quantity, probclass, desc)
VALUES
('$sno', '$date', '$name', '$email', '$supplier', '$PONum', '$Part', '$Serial', '$TSF', '$Quantity', '$probclass', '$desc')";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
header('Location: ../thankyou.php');
}
else {
echo "ERROR";
}
// close mysql
mysql_close();
?>
First you should change
mysql_connect("$host", "$username", "$password") or die("cannot connect");
to:
$con = mysql_connect($host, $username, $password) or die("cannot connect");
You are calling $con but you never defined it. You want to save your MySQL connection (con) as $con for what you are trying to do here.
You should also really consider upgrading to MySQLi as MySQL is deprecated from PHP and will likely be removed from future versions. Here's a resource to get you started. http://www.php.net/manual/en/book.mysqli.php
Edit July 9 2014: You updated your code, and I do not recall what your original code was. Still, if it's not "working", it's best to describe how it's not working. After you call $result, do this:
if( !$result || !mysql_affected_rows() )
die( mysql_error() );
header('Location: ../thankyou.php'); //this will only occur if there are no SQL errors and the result actually inserted something
mysql_close();
echo "We couldn't forward you automatically. Click here to proceed {insert HTML/JS here}";
This will return the MySQL error message which will help you in your debugging.
You got your argument parsing wrong.
$name = mysql_real_escape_string($con, $_POST['name']);
$con is not defined first of all.
Secondly you are trying to escape $_POST['name'].
mysql_real_escape_string expects 2 arguments, 1st one is mandatory and second one is optional. First argument is the string you want to escape, the second specifies a mysql connection (optional as you may have one open already).
So your statement needs to look like
$name = mysql_real_escape_string($_POST['name']);
Perhaps $con is your mysql connection? Which if it is the case you may want to
$con = mysql_connect ........ and so on
you're using un-secure depreciating methods too. You should research PDO object. It separates variables from your query so they aren't sent at the same time. It also cleans code considerably. I see a few problem areas in his code... You pass in $sno, $date, but they don't exist in your code. $tsf has a different case in instantiation then what you're using in your query. You're using single quotes which can't interpolate data (place values where variable names are). Double quotes do that...
hmmm...
check this out.
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_port = "3306" // Mysql port
$db_name = "report"; // Database name
$dsn = "mysql:dbhost=$host;dbport=$db_port;dbname=$db_name";
//add sno variable declaration here.
$name = $_POST['name'];
$email = $_POST['email'];
$supplier = $_POST['supplier'];
$PONum = $_POST['PONum'];
$Part = $_POST['Part'];
$Serial = $_POST['Serial'];
$TSF = $_POST['tsf'];
$Quantity = $_POST['Quantity'];
$probclass = $_POST['probclass'];
$desc = $_POST['desc'];
$date = date('d-m-Y');
// Connect to server and select database.
$dbConnect = new PDO($dsn, $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sqlStatement = $dbConnect->prepare("INSERT INTO tbl_nonconformance (sno, Date, Name, Email, Supplier, PONum, Part, Serial, TSF, Quantity, probclass, desc)VALUES('?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')");
try{
$sqlStatement->execute(array($sno, $date, $name, $email, $supplier, $PONum, $Part, $Serial, $TSF, $Quantity, $probclass, $desc));
header('Location: ../thankyou.php');
}catch(\PDOException $e){
echo 'Error: Could not connect to db.';
}
?>
PDO object is really easy. create $dbConnect = new PDO(). You see the arguments there. dsn, username, password. The last argument is just an associative array setting PDO's error mode with constants. This allows us to use the try catch block to do error handling. IF PDO can't connect we get the catch block to fire...otherwise the try block which is where our data is sent to the db... You see we have a variable called $sqlStatement.. this is made through $dbConnect->prepare(). This function takes the statement... notice variables are excluded for question marks. Inside the try block we call execute from the statement...this takes and array of values that will replace the question marks in order.
remember to create sno variable. I added date for you. also be sure all cases and spellings are right. One letter in your query string, whether spelled wrong, or even just cased wrong will cause a failure.
let me know if there's any errors or questions. jeremybenson11#gmail.com

php generated form name not posted?

I am trying to make a messaging system for my site. I have this code in my handler php file (which processes the sending of msg):
if($actions=="verstuur"){
//read variables
$naar = $_POST['naar'];//varchar in database. the post = 'ikdekker
$van = $username;//varchar in database. the username = 'user1'
$status = "0";//int in database
if ($_POST['admin'] != ""){
$admin = $_POST['admin'];}else{
$admin=2; //int in database. the post = '0 or 1'
}
$onderwerp = $_POST['onderwerp'];//varchar in database. the post = 'example'
$bericht = $_POST['berichtl'];//varchar in database. the post = 'example message'
$tijd=date("Y-m-d H:i:s");//timestamp in database. the post = '2014-18-1 20:20:20'
// enter is enter
$bericht=nl2br($bericht);
$bericht=eregi_replace("\n","",$bericht);
mysql_query($conn, "INSERT INTO pm (van,naar,status,admin,onderwerp,tijd,bericht) VALUES ('$van','$naar','$status','$admin', '$onderwerp','$tijd','$bericht')");
echo"<script>";
echo"alert('". $actions . "');";
echo "</script>";
}
but it keeps giving me this error:
Warning: mysql_query() expects parameter 1 to be string, resource given in /home/deb70377/domains/cowboycombat.nl/public_html/misc/php/pm_verwerk.php on line 34
cant figure it out, I normally do the html..
You should not use mysql* functions as they are deprecated. Use mysqli* ones:
mysqli_query($conn, "INSERT INTO pm (van,naar,status,admin,onderwerp,tijd,bericht) VALUES ('$van','$naar','$status','$admin', '$onderwerp','$tijd','$bericht')");
Also consider using prepared statements http://lt1.php.net/pdo.prepared-statements
UPADTE
to get the $conn variable you write:
$conn = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
Query first, then the $conn variable

oci_parse() expects parameter 1 to be resource / ociexecute() [function.ociexecute]: ORA-00904

I've recently been working on a uni assignment and had a lot of trouble getting my code to work.
The errors that seem to occur when I upload my .php file onto the server and then try to view them are the following:
Warning: oci_parse() expects parameter 1 to be resource, string given in /home/contactusphp.php on line 227
Warning: ociexecute() expects parameter 1 to be resource, null given in /home/contactusphp.php on line 232
Your mesage has been sent successfully!
Additional details:
This is for use in an Oracle database, and the original purpose was for a user to use a contact form to send a message to the site owner (putting the message into the database).
My code is as follows:
211. <?
212. // extract form data
213. $emailcontact = $_REQUEST['emailcontact'] ;
214. $email_address = $_REQUEST['email_address'] ;
215.
216. // Create the SQL statement to add data into the database
217. $sql = "INSERT INTO contactus (emailcontact, email_address) VALUES ('$emailcontact', '$email_address')";
218.
219. // Set the oracle user login and password info
220. $dbuser = 'XXXX';
221. $dbpass = 'XXXX';
222. $db = 'SSID';
223. $connect = 'OCI_Logon($dbuser, $dbpass, $db)';
224.
225.
226. // Add this data into the database as a new record
227. $stmt = OCI_Parse($connect, $sql);
228. if(!stmt) {
229. echo 'An error occurred in parsing the SQL string./n';
230. exit;
231. }
232. OCI_Execute($stmt); {
233. echo ('Your mesage has been sent successfully!');
234. }
235. ?>
I can't seem to find what could be wrong, and I'm not very experienced with web development either.
EDIT: I got rid of quotes, and changed OCI_Logon/OCI_Parse/OCI_Execute to OCILogon, etc.
However, the problem changed when I did so.
There's a new error code, which is as follows:
Warning: ociexecute() [function.ociexecute]: ORA-00904: "EMAILCONTACT": invalid identifier in /home/contactusphp.php on line 232
The new code is:
211. <?
212. // extract form data
213. $emailcontact = $_REQUEST['emailcontact'] ;
214. $email_address = $_REQUEST['email_address'] ;
215.
216. // Create the SQL statement to add data into the database
217. $sql = "INSERT INTO contactus (emailcontact, email_address) VALUES ('$emailcontact', '$email_address')";
218.
219. // Set the oracle user login and password info
220. $dbuser = 'XXXX';
221. $dbpass = 'XXXX';
222. $db = 'SSID';
223. $connect = OCILogon($dbuser, $dbpass, $db);
224.
225.
226. // Add this data into the database as a new record
227. $stmt = OCIParse($connect, $sql);
228. if(!stmt) {
229. echo 'An error occurred in parsing the SQL string./n';
230. exit;
231. }
232. OCIExecute($stmt); {
233. echo ('Your mesage has been sent successfully!');
234. }
235. ?>
EDIT:
The problem ended up fixing itself, and I have no idea how.
Why the quotes around this function?
$connect = 'OCI_Logon($dbuser, $dbpass, $db)';

Insert Into doesn't work

I want to insert data fields like: id=1, id_page=12356. I read the id_page out of an html document and am always getting this error message:
Warning: mysql_query() expects parameter 1 to be string, resource
given in
/mnt/webi/b0/44/53443744/htdocs/digitalpiano-test/kitareader.php on
line 14 error
<?php
$con = mysql_connect("rdbms.strato.de","U1363575","asdasd123","DB1363575");
if (mysqli_connect_errno())echo "Failed to connect to MySQL: " . mysqli_connect_error();
$name = file_get_contents('kitas.html'); $array_name = explode("<tr>", $name);
foreach($array_name as $value) {
$value2 = explode('<a href="kitaDetails.aspx?ID=',$value);
$value3 = explode('">',$value2[1]);
$id_page = $value3[0];
$eintragen = mysql_query($con,"INSERT INTO kita_berlin (id_page) VALUES ('$id_page')") or die ("error");
} ?>
What is wrong?
MySQL takes the query as the first parameter and the connection as the second parameter.
$eintragen = mysql_query("INSERT INTO kita_berlin (id_page) VALUES ('$id_page')", $con) or die ("error");
This would work, but you really should look at using MySQLi or PDO as MySQL is deprecated now.
Moreover, there's a much cleaner way to get the id_page attribute, by directly using GET, instead of exploding the id_page out.

Categories