I am trying to execute a SQL query and it does not work.
$sql = "SELECT top 5 AccountDocument from web.Preoffers_new where AccountDocument = 'xxxxxxxx'";
$stmt = $db->prepare($sql);
$stmt->execute();
if ($data = $stmt->fetch()) {
do {
echo $data['AccountDocument'] . '<br>';
} while ($data = $stmt->fetch());
} else {
echo 'Empty Query';
}
This works perfectly and shows me the results.
But this:
$sql = "SELECT top 5 Document from Companies where Document = 'xxxxxxxx'";
$stmt = $db->prepare($sql);
$stmt->execute();
if ($data = $stmt->fetch()) {
do {
echo $data['Document'] . '<br>';
} while ($data = $stmt->fetch());
} else {
echo 'Empty Query';
}
Go directly to Empty Query. But is not true because if I execute that query in SQL it works perfectly.
The only diferent i see is the first one query go to a table in the DB and the second one go to a one view...
Some clues could be this?
SET
ANSI_NULLS,
QUOTED_IDENTIFIER,
CONCAT_NULL_YIELDS_NULL,
ANSI_WARNINGS,
ANSI_PADDING
ON;
UPDATE ---->
i set the attribute PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION for see if the server show me something and I received this:
Error conectando con la base de datos: SQLSTATE[HY000]: General error: 1934 General SQL Server error: Check messages from the SQL Server [1934] (severity 16) [SELECT top 5 Document from Companies where Document = 'xxxxxxxx']
I checked the error in SQL and I get this:
%ls failed because the following SET options have incorrect settings: '%.*ls'. Verify that SET options are correct for use with %S_MSG..
Anyone have any idea why I can not make queries in views?
Thanks for reading me :)
As i see in code you use "Document" instead of "AccountDocument" So replace AccountDocument with Document.
$sql = "SELECT top 5 Document from Companies where Document = 'xxxxxxxx'";
$stmt = $db->prepare($sql);
$stmt->execute();
if ($data = $stmt->fetch()) {
do {
echo $data['Document'] . '<br>';
} while ($data = $stmt->fetch());
} else {
echo 'Empty Query';
}
Related
We have a script that pulls queries from a database every couple of minutes. Those results are then shown in a table on a webpage. It works great, until that database responds with an error code (for whatever reason that may be) and instead of stopping it clears all the data. We don't want this data being cleared. It just needs to stop trying to pull if it gets an error message and wait until the next pull. Any idea how we can prevent this clearing all content?
Connection to Database:
<?php
$constr = 'mysql:host=mysql.test.com;dbname=test_custom;charset=utf8';
$dbUser = 'test';
$dbPW = 'test';
try {
$db = new PDO($constr, $dbUser, $dbPW);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$rez = "Connected";
//echo $rez;
} catch(PDOException $ex) {
$rez = "An Error occured connecting to the DB: ".$ex->getMessage().".";
//echo $rez;
}
?>
Code to display the results on the page:
<?php
include 'db.connect.php';
$sql = "SELECT ts_id, position, name FROM ts_applications WHERE enable = 1 ORDER BY Client";
$stmt = $db->prepare($sql);
$stmt->execute();
$num_rows = $stmt->rowCount();
//echo $num_rows;
if($num_rows > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['ts_id'];
$name = $row['name'];
echo "<tr>";
echo "<th><a href='position.php?id=" . $id . "'>" . $name . "</a></th>";
echo "</tr>";
}
} else {
echo "<tr>";
echo "<th>Please <a href='contact.php'>Contact</a> Doh! Something went wrong</th>";
echo "</tr>";
}
include 'db.close.php';
?>
Thank you in advance!
You might try changing your query to:
$sql = "IF EXISTS (SELECT TOP 1 fm_id FROM mb_searches WHERE fm_id IS NOT NULL) SELECT fm_id, position, client, city, state FROM mb_searches WHERE enable = 1 ORDER BY Client";
I don't know if that will filter out your error message
I have an old PHP code that has mysql in it.
It gets an array from a SELECT statement, adds it to a JSON object, as a property and echoes the encoded JSON.
I changed it around to use mysqli, but when I try to get the rows, and create an array out of them, it just returns nothing.
Here's the old mysql code:
$con = mysql_connect('host','account','password');
if (!$con)
{
//log my error
};
mysql_select_db("database_name", $con);
mysql_set_charset('utf8');
$sql = "SELECT field1 as Field1, field2 as Field2 from table where ID = '".$parameter."'";
$query = mysql_query($sql);
$results = array();
while($row = mysql_fetch_assoc( $query ) )
{
$results[] = $row;
}
return $results;
Version1: Here's the new one that I tried writing:
$con = mysqli_connect('host','account','password','database_name');
$sql = "SELECT field1 as Field1, field2 as Field2 from table where ID = '".$parameter."'";
$results = array();
if($result=mysqli_query($con, $sql))
{
while ($row=mysqli_fetch_assoc($result))
{
$results[] = $row;
}
return $results;
}
else
{
//error
}
Version2: Second thing I tried, which only returns 1 ROW:
...same as above until $sql
if($result=mysqli_query($con,$sql))
{
$row=mysqli_fetch_assoc($result);
return $row;
}
Version3: Or I tried to completely mirror the mysql structure like this:
$sql = "SELECT ...";
$query = mysqli_query($con, $sql);
$results = array();
while($row = mysqli_fetch_assoc( $query ) )
{
$results[] = $row;
}
return $results;
Wrapping the resulting array into the JSON:
$obj = new stdClass();
$obj->Data = $results;
$obj->ErrorMessage = '';
die(json_encode($obj)); //or echo json_encode($obj);
None of the mysqli version are working, so I was thinking there might be an important change in the way these arrays are created.
Any tips on what could be wrong on the first mysqli example?
With Version2 I can tell that the SQL connection is there, and I can at least select a row. But it's obviously only one row, than it returns it. It makes me think, that building up the array is the source of the problem, or it's regarding the JSON object...
LATER EDIT:
OK! Found a working solution.
ALSO, I played around with the data, selected a smaller chunk, and it suddenly worked. Lesson from this: the function is not responding the same way for 40 rows or for 5 rows. Does it have something to do with a php.ini setting? Or could there be illegal characters in the selection? Could it be that the length of a 'Note' column (from the db) is too long for the array to handle?
Here's the working chunk of code, that selects some rows from the database, puts them into an array, and then puts that array into an object that is encoded into JSON at the end, with a statusmessage next to it. Could be improved, but this is just for demo.
$con = mysqli_connect('host','username','password','database_name');
if (!$con)
{
$errorMessage = 'SQL connection error: '.$con->connect_error;
//log or do whatever.
};
$sql = "SELECT Field1 as FieldA, field2 as FieldB, ... from Table where ID='something'";
$results = array();
if($result = mysqli_query($con, $sql))
{
while($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
}
else
{
//log if it failed for some reason
die();
}
$obj->Data = $results;
$obj->Error = '';
die(json_encode($obj));
Question is: how can I overcome the issue regarding the size of the array / illegal characters (if that's the case)?
Your "Version 1" seems to be correct from a PHP perspective, but you need to actually handle the errors - both when connecting and when performing the query. Doing so would have told you that you don't actually query a table, you're missing FROM tablename in the query.
Use mysqli_connect_error() when connecting, and mysqli_error($con) when querying to get back the actual errors. General PHP error-reporting might also help you.
The code below assumes that $parameter is defined prior to this code.
$con = mysqli_connect('host','account','password','database_name');
if (mysqli_connect_errno())
die("An error occurred while connecting: ".mysqli_connect_error());
$sql = "SELECT field1 as Field1, field2 as Field2
FROM table
WHERE ID = '".$parameter."'";
$results = array();
if ($result = mysqli_query($con, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
}
return $results;
} else {
return mysqli_error($con);
}
Error-reporing
Adding
error_reporting(E_ALL);
ini_set("display_errors", 1);
at the top of your file, directly after <?php would enable you to get the PHP errors.
NOTE: Errors should never be displayed in a live environment, as it might be exploited by others. While developing, it's handy and eases troubleshooting - but it should never be displayed otherwise.
Security
You should also note that this code is vulnerable to SQL-injection, and that you should use parameterized queries with placeholders to protect yourself against that. Your code would look like this with using prepared statements:
$con = mysqli_connect('host','account','password','database_name');
if (mysqli_connect_errno())
die("An error occurred while connecting: ".mysqli_connect_error())
$results = array();
if ($stmt = mysqli_prepare("SELECT field1 as Field1, field2 as Field2
FROM table
WHERE ID = ?")) {
if (mysqli_stmt_bind_param($stmt, "s", $parameter)) {
/* "s" indicates that the first placeholder and $parameter is a string */
/* If it's an integer, use "i" instead */
if (mysqli_stmt_execute($stmt)) {
if (mysqli_stmt_bind_result($stmt, $field1, $field2) {
while (mysqli_stmt_fetch($stmt)) {
/* Use $field1 and $field2 here */
}
/* Done getting the data, you can now return */
return true;
} else {
error_log("bind_result failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("execute failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("bind_param failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("prepare failed: ".mysqli_stmt_error($stmt));
return false;
}
References
http://php.net/mysqli.prepare
How can I prevent SQL injection in PHP?
I am trying to get the results from a query which should get multiple results and display them all on the page. However it is not displaying any of the content. My guess is a mistake in my syntax for me loop. But I am unsure.
//query to find comments about this map
$query = "
SELECT
user_id,
comment
FROM map_comments
WHERE
map_id = :mapID
";
//query parameters
$query_params = array(
':mapID' => $_SESSION['mapID']
);
try
{
//execute query
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
//get all results
$comments = $result->fetchAll;
if($result === FALSE)
{
die(mysql_error()); // TODO: better error handling
}
}
catch(PDOException $e)
{
die("failed to find comments");
}
foreach($comments as &$comment)
{
echo $comment;
}
You need parentheses after a function to call it.
$comments = $result->fetchAll;
should be:
$comments = $statement->fetchAll();
Also, the check for if ($result == FALSE) should be before this line. And you can't use mysql_error() if you're using PDO, you should use $statement->errorInfo(). Or you should enable PDO::ERRMODE_EXCEPTION on the connection, and the catch block will be invoked. You should then use $db->errorInfo() in the error message that it prints.
New to mySQL PDO. I have read other answers here and read tutorials and am finally taking the plunge. Problem is I cannot seem to output data. Hence, can someone assess my code to ensure it is correct? Also, is the system I am using to query the db efficient and clean and secure? thanks
$pdo --- the correct connection information is in this line but has been removed ---
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// SELECT sql query
try {
$thedate='2013-06-03';
$rotation=1;
$stmt = $pdo->prepare("SELECT * FROM sched_main_2013 WHERE thedate=:thedate AND rotation=:rotation");
$stmt->bindValue(':thedate', $thedate, PDO::PARAM_STR);
$stmt->bindValue(':rotation', $rotation, PDO::PARAM_INT);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
}
catch(PDOException $ex) {
echo $ex->getMessage();
}
while($rows = $stmt->fetch()) {
echo $rows['thedate'] . "\n";
echo $rows[assignedRad] . "\n";
echo $rows[rotation] . "\n";
}
// close the connection
$pdo = null;
This code outputs nothing. No errors. Nothing at all.
By the way, the table exists and the SELECT * FROM works fine when I manually run the mySQL statement, so data does exist with this query.
Try
while($rows = $stmt->fetch()) {
echo $rows['thedate'] . "\n";
echo $rows[assignedRad] . "\n";
echo $rows[rotation] . "\n";
}
To
while($rows = $stmt->fetch()) {
echo $rows['thedate'] . "\n";
echo $rows['assignedRad'] . "\n";
echo $rows['rotation'] . "\n";
}
Debug 01
Maybe you can try this to test whether you truly receive any data from database
print_r($stmt->fetchAll());
Instead of your while-loop
Debug 02
Try the simple query that you strongly believe there will be no SQL error for example:
SELECT * FROM sched_main_2013
Without any value binding.
Debug 03
Try another query with WHERE condition, but no binding
SELECT * FROM sched_main_2013 WHERE thedate='2013-06-03' AND rotation=1
You told that var_dump($row) gives you FALSE. The documentation says:
The return value of this function on success depends on the fetch type. In all cases, >FALSE is returned on failure.
Add the following line:
while($row = $stmt->fetch()) {
echo $row['thedate'] . "\n";
echo $row['assignedRad'] . "\n";
echo $row['rotation'] . "\n";
}
if($row === FALSE) {
var_dump($stmt->errorInfo());
die();
}
Further note: You originally named the return value of $stmt->fetch() $rows (plural) instead of $row. I'm not sure whether you know that the method will return a single row each time it is called.
What it have to be
$sql = "SELECT * FROM sched_main_2013 WHERE thedate=? AND rotation=?";
$data = array('2013-06-03', 1);
$stmt = $pdo->prepare($sql);
$stmt->execute($data);
$rows = $stmt->fetchAll();
var_dump($rows);
$sql = "SELECT * FROM sched_main_2013";
$data = array();
$stmt = $pdo->prepare($sql);
$stmt->execute(array());
$rows = $stmt->fetchAll();
var_dump($rows);
If second query returns the rows while first doesn't - there is no data found.
If both returns no rows - then it is caused by bad database design which is clearly seen from the table name, which should never have a postfix like this
$result = mysql_query('SELECT * FROM phpfox_education_question where subject_id = 2 and ques_id =1');
var_dump($result);
//var_dump result is :- "resource(64) of type (mysql result)" in localhost and web host,but
while($row = mysql_fetch_array($result))
{
var_dump($row); //**NOTHING DISPLAYED in web host server but in localhost**
}
Give this a try:
$query = "SELECT * FROM phpfox_education_question WHERE subject_id = '2' AND ques_id = '1'";
$result = mysql_query($query) or die(mysql_error()); // <--- added this
echo "Results: ".mysql_num_rows($result)."<br />"; // <--- added this to output result count
while($row = mysql_fetch_array($result))
{
print_r($row); //**NOTHING DISPLAYED in web host server but in localhost**
}
This is used depreciated code btw
Try adding this:
var_dump(mysql_num_rows($result));
To see if there are any rows to be fetched, if not, that's your answer.BTW, in PDO this code looks like this:
$db = new PDO('mysql:dbname=default_db_name;host=127.0.0.1',$user,$pass);
//use prepared statmenets
$stmt = $db->prepare('SELECT * FROM your_db.phpfox_education_question WHERE subject_id = :subject_id AND ques_id = :ques_id');
//pass binds when executing the stmt
$stmt->execute(array(':subject_id' => 2, ':ques_id' => 1));
//number of rows found:
var_dump($stmt->rowCount());
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{//fetch rows as assoc array
var_dump($row);
}
Note that this is a basic example, there's a lot more you can do with PDO
Update:
To get more debugging info, try this:
try
{
$db = new PDO();//connect, pass correct data here
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);//cause PDO to throw PDOExceptions on error
$stmt = $db->prepare('SELECT * FROM your_db.phpfox_education_question WHERE subject_id = :subject_id AND ques_id = :ques_id');
$stmt->execute(array(':subject_id' => 1, ':ques_id' => 2));
var_dump($stmt->rowCount());
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
var_dump($row);
}
}
catch(PDOException $e)
{
echo $e->getMessage();
$db = null;
return;
}
echo 'No problems with query<br/>';
$db = null;//disconnecto
Make sure no errors are being thrown, if there are, check the messages, find out what is going wrong and fix it. If you can't find a way to fix them, we're here to help, of course.