mysql query and result statement in a function - php

I am wondering I have been trying to place me MySQL query and MySQL result code into a PHP function like this
function setting($claim){
$query = "SELECT `cases`, `hg`, `surname`, `firstname`, `type`, `claim`, `charge`, `damage`, `payment`, `repair`, `returned`, `comments`, `cost` FROM `rep_log` WHERE claim='$claim'";
$result = mysql_query($query) or die(mysql_error());
}
I'm trying to use this so that I can make it easier to change what is being selected without having to have heaps of different variables and stuff just to change the query... so basically what I do is
echo setting("warrenty");
But I'm getting an error:
Warning: mysql_fetch_row() expects parameter 1 to be resource, string given in ...
So I am wondering is it even possible to put a MySQL query and result into a function or is it just something which cannot happen...
If it is possible any help would be great.
COMPLETE CODE
<?
// connection with the database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "netbookdb";
$result="";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
// require the PHPExcel file
require 'Classes/PHPExcel.php';
// simple query
function setting($claim){
$query = "SELECT `cases`, `hg`, `surname`, `firstname`, `type`, `claim`, `charge`, `damage`, `payment`, `repair`, `returned`, `comments`, `cost` FROM `rep_log` WHERE claim='$claim'";
$result = mysql_query($query) or die(mysql_error());
}
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Insurance');
echo setting('Warrenty');
$rowNumber = 1;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
// Save as an Excel BIFF (xls) file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="myFile.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit();
echo 'a problem has occurred... no data retrieved from the database';
?>

You are not returning any result out of a function.
Use return $result;
UPDATE 1:
You have not decalred the $result variable which you are trying to use in mysql_fetch_row so first return the value from the function assign it and then use it.
UPDATE 2:
function setting($claim){
$query = "SELECT `cases`, `hg`, `surname`, `firstname`, `type`, `claim`, `charge`, `damage`, `payment`, `repair`, `returned`, `comments`, `cost` FROM `rep_log` WHERE claim='$claim'";
$result = mysql_query($query) or die(mysql_error());
return $result;
}
and then get the output of function in a variable which you are using in mysql_fetch_row method. i.e.
$result = setting('Warrenty');
Hope this helps.

You are assigning a local "$result" variable, so "mysql_fetch_row($result)" is using the string variable "$result", initialized as "$result = ''", that is not a resource and therefore will raise the exception.
In the "setting" function, put add "global $result;" line:
function setting($claim){
global $result;
$query = "...;
...
}

Related

retreiving recently updated SQL records in php

Is it possible to update the database and then fetch a new recordset right after that will have all this new data entered? Do I need some kind of closure to make sure the insert sql has completed before doing a new SELECT that will contain all the new records?
Ie, put simply, if I have 50 000 entries in total with a structure like this:
$sql = "INSERT INTO `acc_change`(`ID`, `type`, `name`, `amount`, `date`, `processed`)
VALUES (NULL, 'auto', 'Lorem', '75.00', '2018-04-05 00:00:00', 'no'),
(NULL, 'auto', 'Ipsum', '12.00', '2018-04-25 00:00:00', 'no'),(NULL, 'auto', 'Dolor', '24.00', '2018-04-28 00:00:00', 'no')...
INSERT INTO `videos`(`ID`, `type`, `name`, `date`, `processed`)
VALUES (NULL, 'auto', 'Lorem', '2018-04-05 00:00:00', 'no')...
Will I then be able to do something like this:
$update_sql = "SELECT * FROM `acc_change` where `date` < '2018-04-23 12:32:00'"
$sqlMsg = enterSql($update_sql);
and get all the recently added records?
IMPORTANT:
Normally I'd:
pull old data from the database and save it in arrays/objects
pull the new data and save in arrays/objects.
filter out what I need and make new arrays/objects.
create new insert SQL statements.
I am perfectly aware that this is a sollution to the problem, but that is NOT what I am asking. I am asking if/how you can insert/update and then access that new data right away.
My database functions:
function db($action){
static $conn;
$servername = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "life2020";
if ($action == "use"){
if ($conn === null){
$conn = mysqli_connect($servername, $dbuser, $dbpass, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
return $conn;
} else {
mysqli_close($conn);
}
}
function get_db_rows($sql){
$rows = array();
$conn = db("use");
$result = mysqli_query($conn, $sql) or die("Erro!: " . mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
}
mysqli_free_result($result);
return $rows;
}
function enterSql($sql){
$sqlMsg = "";
$conn = db("use");
if (mysqli_multi_query($conn, $sql)) {
$sqlMsg = "Entered data";
} else {
$sqlMsg = "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
return $sqlMsg;
}
SELECT * FROM table_name ORDER BY id DESC,LIMIT 2.

PHP MySQL Query Where x = $variable from function

Why is this not working:
function listOrderComments ($factnr){
global $connection;
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
When I echo $factnr I get "123" back.
When I uncommented //$factnr = 123; my function is working.
Looked everywhere for a solution. check the type $factnr is (string).
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.
If you're going to be using that variable I would recommend you use bind_param for your query
Read the PHP manual link below and you will be able to figure out the issue
http://php.net/manual/en/mysqli-stmt.bind-param.php
If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.
public function listOrderComments ($factnr)
{
global $connection;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
$sql->prepare($query);
$sql->bind_param("s", $factnr);
$sql->execute();
$result = $sql->get_result();
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($data as $row) {
print_r($row);
}
}
Then do what you want with the result
You can go with:
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.
Here is an example of the code you would use.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$factnr = "123" // or where-ever you get your input from.
$query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("factnr" => $factnr);
$statement->execute($statementInputs);
//Returns results as an associative array.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
//Shows array of results.
print_r($result);
?>
Use it correctly over "doted" concat. Following will just work fine:
$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
UPDATE:
here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.
function listOrderComments ($factnr){
global $connection;
if (!is_int($factnr)) return -1
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);

PHP mysqli_fetch_assoc not doing returning correct value

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?

Get mysql result and using it in a subsequent insert command within the same script

So I am having a difficult time getting a variable using a mysql search command and then using it in the same script in an insert command. What am I doing wrong?
<?php
$usto= $_GET["usto"];
$itena= "item";
$sql = 'SELECT sname FROM login';
$hostname_Database = "blocked";
$database_Database = "blocked";
$username_Database = "blocked";
$password_Database = "blocked";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if ($result) {
$row = $result->fetch_assoc();
$sql = "INSERT INTO pon(mis, take)
VALUES({$row['snake']}, '" . $usto . "')"; //Here, I am trying to use the result from the previous select statement for the variable
$result = $mysqli->query($sql);
if ($result) {
...etc.
}
}
?>
You are vulnerable to SQL injection attacks. Read up about those and fix your code FIRST.
After that, realize that ->query() calls return a result HANDLE, not the actual field(s) you'd requested in your query. You have to FETCH a row of data first:
$result = $mysqli->query($sql);
$row = $result->fetch_assoc();
$sql = ".... VALUES ({$row['name_of_field']} ...)";
Note that this is STILL vulnerable to SQL injection.. it's purely to illustrate the query/fetch/insert process.

PHPExcel: Invalid cell coordinate A when inserting Excel into SQL database

In PHP, I am looping through an excel file and inserting it into an MSSQL database. I am getting this error:
Uncaught exception 'PHPExcel_Exception' with message 'Invalid cell coordinate A'
I don't get this error if I only run one of the queries in the loop. Separately, both queries work. So I am pretty sure it has to do with the fact that the 2 queries are running. With the following code, there is one row inserted in both tables and then the error. Any ideas on how to fix this?
Heres the code...
$dbc = odbc_connect(DB_DRIVER, DB_USER, DB_PASSWORD);
$inputFileName = 'lib/test.xlsx';
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 2; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$name = ms_escape_string($rowData[0][0]);
$city = ms_escape_string($rowData[0][2]);
$state = ms_escape_string($rowData[0][3]);
$phone = ms_escape_string($rowData[0][4]);
$website = ms_escape_string($rowData[0][5]);
$profit_status = ms_escape_string($rowData[0][6]);
$query = "insert into account2 ([name], [city], [state], [phone], [website], [type], [created_by], [last_modified_by])
values ('$name', '$city', '$state', '$phone', '$website', '6', '3', '3')
SELECT SCOPE_IDENTITY() AS ins_id";
$data = odbc_exec($dbc, $query);
if (odbc_next_result($data)){
while ($row = odbc_fetch_object($data)) {
$account_id = $row->ins_id;
}
$query = "insert into account_hic2 (account_id, profit_status)
values ('$account_id', '$profit_status')";
}
$data2 = odbc_exec($dbc, $query);
odbc_free_result($data);
odbc_free_result($data2);
}
The error message suggests that you're mis-setting the value of $row at some point, perhaps setting it to null, or to an empty string...
... or perhaps to a resource, as you're using the same variable name in your database fetch in the same loop where you're using it to keep track of the Excel row number

Categories