Retrieve SQL statement from MySQL and process in PHP - php

I have successfully saved a number of SQL UPDATE statements to MySQL and now I want to retrieve them and have PHP process them. The code is below.
When I echo $query I get the correct SQL statements from the DB, but then when I try to process them, I get an error Warning: mysqli_query() [function.mysqli-query]: Empty query
It makes no sense to me and is driving me nuts! Do I have to do something else to $query so PHP can process it?
$num_rows = mysqli_num_rows($resultSQL);
if ($num_rows > 0)
{
while ($row = mysqli_fetch_array($resultSQL))
{
$strSQLupd[] = $row['uSQL'];
}
foreach ($strSQLupd as $query) {
$resultSQLupd = mysqli_query($link,
$query
);
if (!$resultSQLupd)
{
$error = 'Error fetching data: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
}
}

Are you setting the value of $link somewhere and is it required for what you're doing in this application? Also, remember that var_dump($varname); is always a helpful debugging tool.
foreach ($strSQLupd as $query) {
// put a var_dump below
var_dump($query);
$resultSQLupd = mysqli_query($query
);
if (!$resultSQLupd)
{
$error = 'Error fetching data: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
}
Give this a shot and look at the query string dumped to the screen. It may be null which is what's producing your error.

Related

SQL print/echo dumping php code into HTML

I am very, very new to HTML/PHP so I'm probably going to misuse terminology, bear with me please.
I'm trying to print the results of my SQL query in HTML in a <p> element using <br> to separate them. I know it's not the best way but it's an easy one and will help me practice this.
Anyway my problem is instead of printing the "movieName" attribute I'm trying to print it dumps some of the PHP code into the <p> element body instead.
I don't know what information to provide to make it easier on you to spot the problem so please request any relevant details.
Here's the php code (I've "censored" my info because you can easily access my student account with it):
<?php
if (array_key_exists('searchInput', $_GET)) {
$search = $_GET['searchInput'];
// Connecting, selecting database
$dbconn = pg_connect("host=**** port=15432 dbname=**** user=**** password=****")
or die('Could not connect: ' . pg_last_error());
// Performing SQL query
$query = "SELECT movieName
FROM DatabaseProject.Movie M
WHERE M.movieName LIKE $search";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$field = $row["movieName"];
print("$field<br>");
}
} else {
print("0 results");
};
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
}
?>
This is what I get printed into the webpage:
num_rows > 0) { // output data of each row
while($row = $result->fetch_assoc()) {
$field = $row["movieName"];
print("$field
");
}
} else {
print("0 results");
};
// Free resultset pg_free_result($result);
// Closing connection pg_close($dbconn);
}
?>

MYSQL assign column name to variable?

I have a database table which has two columns, business and tourist.
I ask a user to select one of them from dropdown list, then use the result in a SELECT statement in MySQL. I assign this column to $cclass, then I make this statement SELECT $cclass FROM flights ....
But it always returns NULL. Why does it return NULL and how do I fix this?
My code:
$check = mysql_query("SELECT $cclass FROM flights WHERE flight_no = '$flightno'");
while ($result = mysql_fetch_assoc($check))
{
$db_seats = $result['$cclass'];
}
you should replace this line:
$db_seats = $result['$cclass'];
with this:
$db_seats = $result[$cclass];
string between 2 single quotes doesn't parsed:
Strings
Have you tried doing the following:
$check = mysql_query("SELECT".$cclass." FROM flights WHERE flight_no = '$flightno'");
First of all, this code has a serious security issue, as it is vulnerable to SQL Injection. You should be using the MySQLi extension instead, and properly filtering your input.
Try something like this:
<?php
/* Create the connection. */
$mysql = new mysqli("localhost", "username", "password", "myDB");
if ($mysql->connect_error)
{
error_log("Connection failed: " . $mysql->connect_error);
die("Connection failed: " . $mysql->connect_error);
}
/* Sanitize user input. */
if (!in_array($cclass, array('business', 'tourist')))
{
error_log("Invalid input: Must be 'business' or 'tourist'");
die("Invalid input: Must be 'business' or 'tourist'");
}
$statement = $mysql->stmt_init();
$statement->prepare("SELECT $cclass FROM flights WHERE flight_no = ?");
$statement->bind_param("s", $flightno);
if (!$statement->execute())
{
error_log("Query failed: " . $statement->error);
die("Query failed: " . $statement->error);
}
if ($statement->num_rows < 1)
{
echo "No results found.";
}
else
{
$statement->bind_result($seats);
while ($statement->fetch())
{
echo "Result: $seats";
// Continue to process the data... You can just use $seats.
}
}
$mysql->close();
However, the reason your original example is failing, is that you're quoting $cclass:
$db_seats = $result[$cclass];
However, please do not ignore the serious security risks noted above.

How to work with data from mysql in php-multidimensional array

I get null values when I run this code
$dataArray = mysql_query ("SELECT * from _$symbol order by date DESC limit 10;");
while ($ArrayData = mysql_fetch_assoc($dataArray)) {
$dayData [] = $ArrayData;
}
$todaysdate = $dayData[0]['date'];
$volPercentAVG = $dayData[0]['volume'] / $dayData[0]['_50dayVol'];
mysql_query ("update _$symbol set volPercentAvg=$volPercentAVG WHERE date=$todaysdate;");
It does not return anything, I am not sure I am approaching the MDarray correctly? I have triple checked the column names.
Anywhere to do with this would be helpfull
Thanks.
#Fred-ii- YOU DID IT! Can I or you make this an answer so I can vote for it? If I can I dont see how. – illcrx
Posting my comment as the answer in order to close the question.
If your date column contains any spaces or dots etc. then change WHERE date=$todaysdate
to/and quoting it WHERE date='$todaysdate'
For example: 2014-10-06 22:59:52
Would explain why you were not getting results.
However, I'm quite surprised/baffled that MySQL did not throw you a syntax error, bizarro.
Don't have time to read your entire bit right now, but I can give you my test method from our standard mysqli execution set:
print_r($Record);
This will allow you to see the structure and possibly where your error lies.
I'll also give you our framework which can be very useful (which is why we have it! LOL). Example framework (two functions) to make it easier to use mysqli in php with two lines for each query. It also allows for CLI or web output and debugging which will dump the query (so you can run it) and shows a print_r function to show results.:
This goes at the top:
define('DEBUG', false);
define('CLIDISPLAY', false);
if (CLIDISPLAY) {
define('PRE', '');
define('PRE_END', '');
} else {
define('PRE', '<pre>');
define('PRE_END', '</pre>');
}
require_once("/etc/dbconnect.php");
$DBLink = new mysqli($VARDB_server, $VARDB_user, $VARDB_pass, $VARDB_database, $VARDB_port);
if ($DBLink->connect_errno) {
printf(PRE . "Connect failed: %s\n" . PRE_END, $DBLink->connect_error);
exit();
}
Be sure you have a normal php file at /etc/dbconnect.php with your credentials in it (do not put these in a web folder in case php fails one day and exposes your passwords! LOL). Note that this file can then be shared and loaded only once. It should invoke
# Sample execution
$Query = "select * from vicidial_users where user='6666' and active='Y' limit 1";
$Records = GetData($DBLink, $Query);
print_r($Records[0]); // Single record return access via [0] to access a field named "id": $Records[0]['id']
// Multiple record return access via array walking
foreach ($Records as $Record) {
print_r($Record);
}
$Query = "update vicidial_users set active='Y' where user='6666' limit 1";
UpdateData($DBLink, $Query);
Functions (can be loaded from the credentials file or within your working file or put in a "functions.php" file and "require_once('functions.php');".
function GetData($DBLink, $Query) {
if (DEBUG) {
echo PRE . "Query: $Query\n" . PRE_END;
}
if ($Result = $DBLink->query($Query)) {
if (DEBUG) {
printf(PRE . "Affected rows (Non-Select): %d\n" . PRE_END, $DBLink->affected_rows);
}
while ($Record = $Result->fetch_assoc()) {
$ReturnData[] = $Record;
}
return $ReturnData;
} else {
if (DEBUG) {
printf(PRE . "Errormessage: %s\n", $DBLink->error);
printf("Affected rows (Non-Select): %d\n", $DBLink->affected_rows);
echo "No Records Returned\n" . PRE_END;
}
return false;
}
}
function UpdateData($DBLink, $Query) {
if (DEBUG) {
echo PRE . "Query: $Query\n" . PRE_END;
}
if ($Result = $DBLink->query($Query)) {
if (DEBUG) {
printf(PRE . "%s\n", $DBLink->info);
printf("Affected rows (Non-Select): %d\n" . PRE_END, $DBLink->affected_rows);
}
return;
} else {
if (DEBUG) {
printf(PRE . "Errormessage: %s\n", $DBLink->error);
printf("Affected rows (Non-Select): %d\n", $DBLink->affected_rows);
echo "No Records Returned\n" . PRE_END;
}
return;
}
}

Can I improve my PDO method (just started)

I just switched to PDO from mySQLi (from mySQL) and it's so far good and easy, especially regarding prepared statements
This is what I have for a select with prepared statement
Main DB file (included in all pages):
class DBi {
public static $conn;
// this I need to make the connection "global"
}
try {
DBi::$conn = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuname, $dbpass);
DBi::$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
DBi::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo '<p class="error">Database error!</p>';
}
And in my page:
try {
$sql = 'SELECT pagetitle, pagecontent FROM mypages WHERE pageid = ? LIMIT 1';
$STH = DBi::$conn->prepare($sql);
$STH->execute(array($thispageid)); // $thispageid is from a GET var
}
catch(PDOException $e) {
echo '<p class="error">Database query error!</p>';
}
if ($STH) { // does this really need an if clause for it self?
$row = $STH->fetch();
if (!empty($row)) { // was there found a row with content?
echo '<h1>'.$row['pagetitle'].'</h1>
<p>'.$row['pagecontent'].'</p>';
}
}
It all works. But am I doing it right? Or can I make it more simple some places?
Is using if (!empty($row)) {} an ok solution to check if there was a result row with content? Can't find other decent way to check for numrows on a prepared narrowed select
catch(PDOException $e) {
echo '<p class="error">Database query error!</p>';
}
I would use the opportunity to log which database query error occurred.
See example here: http://php.net/manual/en/pdostatement.errorinfo.php
Also if you catch an error, you should probably return from the function or the script.
if ($STH) { // does this really need an if clause for it self?
If $STH isn't valid, then it should have generated an exception and been caught previously. And if you had returned from the function in that catch block, then you wouldn't get to this point in the code, so there's no need to test $STH for being non-null again. Just start fetching from it.
$row = $STH->fetch();
if (!empty($row)) { // was there found a row with content?
I would write it this way:
$found_one = false;
while ($row = $STH->fetch()) {
$found_one = true;
. . . do other stuff with data . . .
}
if (!$found_one) {
echo "Sorry! Nothing found. Here's some default info:";
. . . output default info here . . .
}
No need to test if it's empty, because if it were, the loop would exit.

PHP newbie with a perplexing piece of code

this ought to be simple, but it doesn't seem to be working for me. i have tested it with good and bad passwords. no matter what, it will not go into the else statement. i am not sure what i am missing
my code:
$mysqli = mysqli_connect("localhost", "joeuser", "somepass", "testDB");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$sql = "SELECT * FROM login_info";
$res = mysqli_query($mysqli, $sql);
if ($res) {
while ($newArray = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$id = $newArray['first_name'];
$testField = $newArray['last_name'];
echo "The ID is ".$id." and the text is ".$testField."<br/>";
}
} else {
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
}
mysqli_free_result($res);
mysqli_close($mysqli);
}
If i send it a user and password that do exist it does the if statement fine, but if i send it a test for one that is not in the db it still won't do the else? why?
For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a MySQLi_Result object.
A query is only not successful if some serious error occurred. Simply because a SELECT query didn't match any rows doesn't make the query unsuccessful. You'll still get a MySQLi_Result object back. You'll want to check with mysqli_num_rows whether the result set contains any rows.
BTW, save yourself some nesting:
if (!$something) {
exit;
}
// continue as usual
No need for an else here, since you're exiting anyway. Makes things simpler.
Like this:
if ($res) {
while ($newArray = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$id = $newArray['first_name'];
$testField = $newArray['last_name'];
echo "The ID is ".$id." and the text is ".$testField."<br/>";
}
}
if (!isset($id)) {
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
}

Categories