PHP Connection To Azure-SQL Database - php

In the below code, I try to connect to an azure-sql database with PHP, and in the first part of the if, I write out if the connection failed, which I don't receive. In the next else, I write out if the connection passed, which I get the message on ("Connection succeeded"). This appears to connect correctly; however, I do get an output of 0 even though it clearly hits this part of the else. I can't tell from research if 0 means success, but if it the connection failed, wouldn't it hit the first part of the if?
The problem is that this code isn't outputting the array column added to the string, so it appears that while it's registering as succeeding, it's actually failing, or something else is wrong, like the syntax.
<?php
/// Test variable
$writeOutResult = "Result: ";
/// VARIABLES NOT INCLUDED
/// Connect
$connInfo = array("Database"=>$azureDB
, "UID"=>$azureUser
, "PWD"=>$azurePass
, "MultipleActiveResultSets"=>true
);
$conn = sqlsrv_connect($azureServer,$connInfo);
/// Test connection
if($conn === false)
{
//FatalError("Server unavailable.");
$writeOutResult = "Connection failed.";
}
else
{
echo "Connection succeeded";
$get = sqlsrv_query($conn,$query);
while ($row = sqlsrv_fetch_array($get, SQLSRV_FETCH_ASSOC))
{
$writeOutResult += $row["Column"];
}
}
?>
<html>
<head><title></title></head>
<body>
<p>Output:</p>
<?php
echo $writeOutResult;
?>
</body>
</html>

It seems that there is no obvious error on PHP. I tested on my side and which worked fine.
It could be the case of following causes, you can check one by one.
Please check the SQL query stmt, whether it's correct, you can query it in SSMS for verification.
Check the value and data type. Whether it can be plus directly.
Any further concern, please feel free to let me know.

Related

Trying to perform 2 php inserts on the same database connection

Full disclosure, I am a php noob my background is in .NET dev
So I have the following php code:
if ($conn->query($insert_listing) === TRUE) {
$listing_id = $conn->insert_id;
}
else {
echo "Error: " . $conn->error;
}
then I build my second query and then I have the following code:
if ($conn->multi_query($insert_times) === TRUE) {
echo = "times inserted";
}
else {
echo = "Error: " . $conn->error;
}
$conn is the variable holding my database connection and I know the connection is fine because the first bit of code runs fine if the second is commented out. I also know that the queries held in $insert_listing and $insert_times are correct as I have echoed them and run them in my database engine. When I try and load my page I get a 500 server error.
As a side note is there a way I can get the actual 500 error message so I have a better idea of where to look to troubleshoot the issue?
EDIT: Problem solved! Found the error log, lead me to the problem, I was accidentally assigning to echo in the second code fragment!
Your error is here:
echo = "times inserted";
You cannot assign to echo, I guess you meant:
echo "times inserted";

PHP - MySql Database info not storing

I have been trying to figure this out for hours, I have created a database ( MySql/PHPMyadmin) and i am trying to get user input stored to be able to call back up, however the info is not making it/ saving it to the database, everything shows up okay except this part of code:
$registered = mysqli_affected_rows ($dbc);
echo $registered. "Row is affected";
when run gives me a display of -1 row, I believe this to be a big part of the problem as everything else seems to work okay. I am a complete beginner so could you guys tell me how the best way of debugging this is.
$dbc = $dbc = mysqli_connect ($hostname, $username, $password, $dbname) OR die("Could not Connect");
To input the data to the db i have the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$comments = $_POST ['Comments'];
if (!empty ($comments)){
include ('mysqldb.php');
mysqli_query ($dbc,"INSERT INTO 'User-Comments' (Comments) VALUES ('$comments')");
$registered = mysqli_affected_rows ($dbc);
echo $registered. "Row is affected";
}else {
echo "Nothing Submitted";
}
}
The line:
mysqli_query ($dbc,"INSERT INTO 'User-Comments' (Comments) VALUES ('$comments')");
should be:
mysqli_query ($dbc,"INSERT INTO `User-Comments` (Comments) VALUES ('$comments')");
Notice the change in the apostrophe character ( ` ) around your table name.
An excerpt from the documentation for function mysqli_stmt_affected_rows(): -1 indicates that the query has returned an error.
You should check the value returned by mysqli_query(). If it returns FALSE then you can get details about the reason (error message) by using function mysqli_error().

Warning: mysqli_query(): Couldn't fetch mysqli in C:\ ... on line 13

although this question has been asked (and answered) many times, I didn't find a solution to the problem.
Here is my code:
<?php
#session_start();
include("./include/config.php");
include("./include/db_connect.php");
include("functions.php");
if (!isset($_GET['artikelID'])){$_GET['artikelID'] = "";}
if (!isset($_SESSION['UserID'])){$_SESSION['UserID'] = "";}
$sql = "SELECT kundenID FROM kunden WHERE username = '".$_POST['myusername']."' AND password = '".md5($_POST['mypassword'])."' ";
$result = mysqli_query($connect, $sql) OR die("<pre>\n".$sql."</pre>\n".mysqli_connect_error()); // this is line 13
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result)==1){
doLogin($row['kundenID'], isset($_POST['Autologin']));
header("location:cart.php?action=add&artikelID=".$_GET['artikelID']."&id=". $_SESSION['UserID'] ." ");
}
else {
header("location:k_login.php?error=TRUE ");
}
include("./include/db_close.php");
?>
mysqli_connect_error() shows me the absolute correct sql-query; the sql-query is tested with a tool named mysql-front and brings exactly one (and the correct one) result, which is 'kundenID'.
I have tested many things (like $_SESSION['connect'] or $_GLOBALS['connect'] instead of $connect in db_connect.db), but with no result.
Can anyone please help me?
-- Update --
Why does nobody answer?
Is the description of the problem unclear?
The db-connection is established like this:
<?php
error_reporting(E_ALL);
$connect = mysqli_connect($dbserver,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno()){
echo "Zeile ".__LINE__.": Datenbankverbindung ist fehlgeschlagen ! " . mysqli_connect_error();
exit();
}
?>
All the db-variables are known in the checklogin-script (tested). All the $_POST-variables are also known in the checklogin-script (tested). I even tried a hard-coded sql-query (with the real data of the test-record in the db).
The result is still the same: mysqli_connect_error() reports the correct query - but then nothing more happens.
I have spent more than 10 hours in the meantime. I really would appreciate, if someone could help me.
Couldn't fetch mysqli means that PHP is unable to identify the contents of your $connect variable as a valid mysqli connection. Try adding some error handling into "./include/db_connect.php" to get an idea of what happened to the mysqli connection that is preventing you from using it.

SQL syntax error

Im fairly new to both PHP and SQL but what i want is for the details entered into my form to be inserted into a database.
The code i have written works and the data is submitted into the database but there are a couple things not right.
Firstly here is the code;
<?php
include "credentials.php";
function insert_post($cnhost,$cnusername,$cnpassword,$cndatabase,$titlein,$contentin,$comment_optionin) {
$connect = mysqli_connect($cnhost,$cnusername,$cnpassword,$cndatabase);
if (mysqli_connect_errno($connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo "Connection Success! <br>";
$submitpost_query = mysqli_query($connect,"INSERT INTO blog_posts (title,content,comment_option) VALUES ('".$titlein."','".$contentin."','".$comment_optionin."')");
if (!mysqli_query($connect,$submitpost_query))
{
die('Error: ' . mysqli_error($connect));
}else{
echo "Post submitted.";
}
mysqli_close($connect);
}
}
$title = $_POST["title"];
$content = $_POST["content"];
$comment_option = $_POST["comment_option"];
insert_post($host,$username,$password,$database,$title,$content,$comment_option);
?>
Although the data is submitted into the database as i want i get the following error;
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1"
The $comment_option variable contains the value 1 or 0, depending on which radio button is selected so this error might be referring to this variable but this SQL error is the same whether the value of $comment_option is 1 or 0.
I do see "Connection success!" before this error but do not see "Post submitted" even though the post is actually submitted. Any ideas why?
As well as helping me with this problem i would be very grateful if somebody could give me some general tips to improve what iv wrote. I am a noob so im sure there's a few things that could be improved here!
Thanks very much!
The problem is here:
if (!mysqli_query($connect,$submitpost_query))
You're passing a mysqli_query result which is $submitpost_query to another mysqli_query which is in the if statement.
The problem is with following chunk of code
if (!mysqli_query($connect,$submitpost_query))
it should be instead following
if (!$submitpost_query)
Reason : You are executing return object again through mysql_queri function that is causing warning, invalid resource, as this function only excepts valid sql query or connection object
I know your question is answered but I seriously recommend you to sanitize the POST data before concatenating it in a query.

Why is my include tag deleting everything after it?

I have a PHP file included but everything after the <?php include 'RandomFile.php' ?> gets thrown away, I have no clue why! I need help with this.
RandomFile.php has the contents of:
require 'cons.php';
mysql_connect($URL, $USER, $PASS, $DBN);
$strSQL = "SELECT * FROM song";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
if($rs === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['url'] . "<br />";
}
// Close the database connection
mysql_close();
So Basically after the <?php include 'randomfile.php' ?> is included all my html after that isn't showing up visually in my browser but if I go back and edit the file it is there???
I'm guessing that cons.php is the connection file for your database. You need to specify the full path to cons.php. From the PHP Manual for require:
require is identical to include except upon failure it will also
produce a fatal E_COMPILE_ERROR level error. In other words, it will
halt the script whereas include only emits a warning (E_WARNING) which
allows the script to continue.
So this example shows the file at the root.
require ($_SERVER['DOCUMENT_ROOT'].'/cons.php');
If it's below the DocumentRoot then you would do this:
require ($_SERVER['DOCUMENT_ROOT'].'/../cons.php');
On another note, replace all of the mysql_ functions with mysqli_. New versions of PHP will not include it as mysql_ has been deprecated.
Since you are trying a SQL query without selecting a database first, mysql fails with the error "No database selected"
The error is displayed with the code die(mysql_error());. die aborts further execution of the script. If you'd like it to continue you should just print it instead like this
if($rs === FALSE) {
print(mysql_error() . "\n"); // TODO: better error handling
}
else {
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['url'] . "<br />";
}
// Close the database connection
mysql_close();
}
The key is this line:
die(mysql_error()); // TODO: better error handling
If there is an error connecting to the database (as you described in your comment: "no database selected"), the execution will "die" and no more of the page will be sent to the browser.
As the code comment says, you need better error handling, but you might conceivably temporarily change the die to an echo and then the execution will continue.
Are you missing the semicolon (;) in the include?
Btw, you could set
<?php error_reporting(E_ALL);
ini_set('display_errors', '1'); ?>
this will show you the errors in your script.

Categories