Trying to perform 2 php inserts on the same database connection - php

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";

Related

PHP Prepared Statement not inserting, no errors appearing

I am attempting to insert some data via prepared statements in PHP. I have the following code which is not inserting for me. I also have the following code set already
ini_set('display_errors', 1);
error_reporting(~0);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$sqlInsert = "INSERT INTO deck_cards (deckid, cardid, qty) VALUES (?,?,?)";
$stmtInsert = $conn->prepare($sqlInsert);
if ($stmtInsert)
{
$stmtInsert->bind_param("sss", $deckid, $cardid, $cardcount) or trigger_error($stmtInsert->error, E_USER_ERROR);
$stmtInsert->execute() or trigger_error($stmtInsert->error, E_USER_ERROR);
echo "Check if this ran";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
$conn->close();
}
$stmtInsert->close();
}
catch (Exception $ex)
{
echo 'Exception occurred '.$ex->getTraceAsString();
}
When this executes, I do see the text "Check if this ran" but no other messages. The data is not inserted into the database. Additionally, I echo'd the sql string and variables and ran it against the MySQL directly and it inserted ok. Not sure what is happening in my very straightforward code above.
Additionally, inserts are happening ok in other pages within my app, but this page for some reason isn't working.
I know it's overkill on my error reporting, but I threw everything I could think of to see if there is an error somewhere, but this one is a head scratcher for me. Thanks for any assistance!

PHP Connection To Azure-SQL Database

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.

mysql php displays results but not inserting into database

I stripped down query for only one insert
<?php
session_start();
include 'cstring.php';
$title="";
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
$title=$_POST['title'];
$query=mysqli_query($con,"insert into blogpages(blogpagetitle) values('".$title."')");
if($query){
$bloga="sucessfully added a new blog";
echo $bloga;
}
else {
echo mysqli_error($con); // if using mysqli do not use mysql in between
}
}
mysqli_close($con);
?>
is there something wong in this code that it doesnt insert into mysql
table structure
1.bpid int(50)--------------null-no default-none autoincrement
2.blogpagetitle------------varchar(255) utf16_general_ci
3.datemade-------------timestamp current time stamp
4.blogpagedescription---------text utf16_general_ci
5.blogbody----------------longtext utf16_general_ci
6.blogpageextended------------ text utf16_general_ci
TIP
Sanitize variables, Use mysqli_real_escape_string()
When you are not able to debug your code, echo every possible stuff and die the rest code.
For example here, echo if there is error in DB connection, echo the query to see if it is correct, echo the result of query execution, echo if there is some error!
You should be using echo mysqli_error($con) to get the error message rather than mysql_error().

PHP Query causes SQL Server Tables to disappear and reappear

We have a website that accesses a SQL Server 2005 server for one query. Currently, the site is in ASP, we are moving it to PHP, and the PHP one is currently being tested. After we run a few successful queries on the PHP site, it returns the "Error in database query. Please try again later" line in the code below. When I rewrote that line with sqlsrv_errors to elaborate, it told me that the table didn't exist. There are about 40 tables in the database, but after the error happens it only shows 8 of them in Management Studio. However, if I allow it to sit for about 5 minutes, all of the tables are restored. No matter how many times the old ASP site is used, the table does not do this. However, when the tables disappear from using the new site, the old site shows inaccessible for a few minutes until the tables re-appear in SQL Server management studio. I didn't see any kind of connection limits on the SQL Server, so I don't know whether it's something I'm doing in the PHP SQL queries or within the SQL Server properties.
<?php
include ("dbvals.inc.php");
if (!empty($_POST['lastnamebox'])) {
$dbhandle = sqlsrv_connect($dbServer, $connectioninfo);
if($dbhandle == false){
echo "Error connecting to database. Please try again later. ";
}
else{
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
$params = array();
array_push ($params, $_POST['lastnamebox']);
$results = sqlsrv_query($dbhandle, $query, $params);
if($results == false){
echo "Error in database query. Please try again later.";
//This is printed when database tables temporarily disappear
}
else
{
$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
if($row){
do{
echo "<tr><td class='tablecell'>";
echo $row['LastName'] . "," . $row['FirstName'] . "<br>";
echo "Address: " . $row['Address'] . "<br>";
echo "City, State, Zip: " . $row['CSZ'] . "<br>";
echo "</tr></td'>";
}while($row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC));
}
else{
echo "No results found. Please try another query.";
}
}
}
sqlsrv_free_stmt($results);
sqlsrv_close($dbhandle);
}
else {
echo "Please type a value in the search box.";
}
?>
The $query is wrong to begin with. Change it to:
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
Not sure about the tables disappearing though. What driver are you using?
Just another issue I'm seeing with the code not sure if it's related to your problem. or another copy error but here it is.
if ($r1 = sqlsrv_fetch_array($results)) {
while( $row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC)){
The first fetch should also have '($results,, SQLSRV_FETCH_ASSOC)'
Additional that check is going to eat the first returned record which may or may NOT be what you intended.
Also it is possibly that PHP seeing some results in the while as false even though they aren't and the server is still waiting on you to finish getting the rest. Seen code like that cause 'Server has got away' errors in MySQL which could be what is going on here as well.
Not sure of the syntax but a sqlsrv_clode_cursor() just before the connection close might also fix your issue if there's some kind of connection polling going on. Could be simply running out of connection or getting old one in a incorrect state.
SELECT * FROM Person WHERE AND LastName LIKE
Looks like there something missing between the WHERE and AND to me.
I don't know SQL Server really so it could allow that but it's not standard SQL. Depending on how it's reacting to that error I could see it 'Going away' so to say and reporting tables missing.

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.

Categories