PHP 5 display mysql table error - Call to undefined function mysql_results() - variables

I premise I'm new to php. I've tried to create a php page that displays the content of a MySQL database. As I try it in localhost I have this warning:
"Fatal error: Call to undefined function mysql_results() in C:\xampp\htdocs\phplessons\guestbook_displayer_2.php on line 18". It seems the db connection works. Someone have a tip?
This is my code:
<html>
<head></head>
<title>Display MySQL db</title>
<body>
<?php
$db=mysql_connect("localhost","root","mypassword"); //db connection
mysql_select_db ("prova001"); //choose a db
$res=mysql_query("SELECT * from php_guestbook"); //query a table
$num=mysql_num_rows($res);
// begin table
echo "<table border=1>";
echo "<tr><td>Nr.</td><td>First name</td>";
echo"<td>Last name</td><td>Country</td>";
echo"<td>E-Mail address</td><td>Telephone</td></tr>";
// contatore
for ($i=0; $i<$num; $i++)
{
$cg=mysql_results($res,$i,"firstname"); // line 18 this var is undefined.
$nm=mysql_results($res,$i,"lastname"); //Probably also the others have a similar problem.
$np=mysql_results($res,$i,"country"); //Can it be due to a bad record counter?
$st=mysql_results($res,$i,"email");
$tl=mysql_results($res,$i,"telephone");
$lf=$i+1;
//
echo "<tr><td>$lf</td><td>$cg</td><td>$nm</td><td>$np</td><td>$st</td><td>$tl</td></tr>";
}
echo "</table>";
mysql_close($db);
?>
</body>

You have probably made a typo. The method is mysql_result() without 's'.
But, you can shorten your query result handling by this way ;
// query
$res=mysql_query("SELECT * from php_guestbook"); //query a table
// begin table
echo "<table border=1>";
echo "<tr><td>Nr.</td><td>First name</td>";
echo"<td>Last name</td><td>Country</td>";
echo"<td>E-Mail address</td><td>Telephone</td></tr>";
while ($item = #mysql_fetch_assoc($res)) {
// do something with var $item;
$cg = $item['firstname'];
$nm = $item['lastname'];
// ect
}

Related

Square PHP API - Record Data

I am new at this payment API and understanding of Arrays().... I am using Squares PHP API script expample... I like it, however, when it processes the payment, I want to catch certain data and record to sql (mysqli)... I can't even make the script echo the specific data I want... I am lost... Could someone get me in the right direction?
Here is the form: (index.php)
<?php
require '../composer/vendor/autoload.php';
# Replace these values. You probably want to start with your Sandbox credentials
# to start: https://docs.connect.squareup.com/articles/using-sandbox/
# The access token to use in all Connect API requests. Use your *sandbox* access
# token if you're just testing things out.
$access_token = 'sandbox-XXXXXX';
# Helps ensure this code has been reached via form submission
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
error_log("Received a non-POST request");
echo "Request not allowed";
http_response_code(405);
return;
}
# Fail if the card form didn't send a value for `nonce` to the server
$nonce = $_POST['nonce'];
if (is_null($nonce)) {
echo "Invalid card data";
http_response_code(422);
return;
}
\SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$locations_api = new \SquareConnect\Api\LocationsApi();
try {
$locations = $locations_api->listLocations();
#We look for a location that can process payments
$location = current(array_filter($locations->getLocations(), function($location) {
$capabilities = $location->getCapabilities();
return is_array($capabilities) &&
in_array('CREDIT_CARD_PROCESSING', $capabilities);
}));
} catch (\SquareConnect\ApiException $e) {
echo "Caught exception!<br/>";
print_r("<strong>Response body:</strong><br/>");
echo "<pre>"; var_dump($e->getResponseBody()); echo "</pre>";
echo "<br/><strong>Response headers:</strong><br/>";
echo "<pre>"; var_dump($e->getResponseHeaders()); echo "</pre>";
exit(1);
}
$transactions_api = new \SquareConnect\Api\TransactionsApi();
$request_body = array (
"card_nonce" => $nonce,
# Monetary amounts are specified in the smallest unit of the applicable currency.
# This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
"amount_money" => array (
"amount" => 100,
"currency" => "USD"
),
# Every payment you process with the SDK must have a unique idempotency key.
# If you're unsure whether a particular payment succeeded, you can reattempt
# it with the same idempotency key without worrying about double charging
# the buyer.
"idempotency_key" => uniqid()
);
# The SDK throws an exception if a Connect endpoint responds with anything besides
# a 200-level HTTP code. This block catches any exceptions that occur from the request.
try {
$result = $transactions_api->charge($location->getId(), $request_body);
echo "<pre>";
echo "Card has been Approved!";
echo $result['amount'][0];
echo $result['transaction_id'][1];
echo "</pre>";
} catch (\SquareConnect\ApiException $e) {
echo "Caught exception!<br/>";
print_r("<strong>Response body:</strong><br/>");
echo "<pre>"; var_dump($e->getResponseBody()); echo "</pre>";
echo "<br/><strong>Response headers:</strong><br/>";
echo "<pre>"; var_dump($e->getResponseHeaders()); echo "</pre>";
}
And here is the processor (process-card.php)
<?php
require '../composer/vendor/autoload.php';
# Replace these values. You probably want to start with your Sandbox credentials
# to start: https://docs.connect.squareup.com/articles/using-sandbox/
# The access token to use in all Connect API requests. Use your *sandbox* access
# token if you're just testing things out.
$access_token = 'sandbox-XXXXXX';
# Helps ensure this code has been reached via form submission
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
error_log("Received a non-POST request");
echo "Request not allowed";
http_response_code(405);
return;
}
# Fail if the card form didn't send a value for `nonce` to the server
$nonce = $_POST['nonce'];
if (is_null($nonce)) {
echo "Invalid card data";
http_response_code(422);
return;
}
\SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$locations_api = new \SquareConnect\Api\LocationsApi();
try {
$locations = $locations_api->listLocations();
#We look for a location that can process payments
$location = current(array_filter($locations->getLocations(), function($location) {
$capabilities = $location->getCapabilities();
return is_array($capabilities) &&
in_array('CREDIT_CARD_PROCESSING', $capabilities);
}));
} catch (\SquareConnect\ApiException $e) {
echo "Caught exception!<br/>";
print_r("<strong>Response body:</strong><br/>");
echo "<pre>"; var_dump($e->getResponseBody()); echo "</pre>";
echo "<br/><strong>Response headers:</strong><br/>";
echo "<pre>"; var_dump($e->getResponseHeaders()); echo "</pre>";
exit(1);
}
$transactions_api = new \SquareConnect\Api\TransactionsApi();
$request_body = array (
"card_nonce" => $nonce,
# Monetary amounts are specified in the smallest unit of the applicable currency.
# This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
"amount_money" => array (
"amount" => 100,
"currency" => "USD"
),
# Every payment you process with the SDK must have a unique idempotency key.
# If you're unsure whether a particular payment succeeded, you can reattempt
# it with the same idempotency key without worrying about double charging
# the buyer.
"idempotency_key" => uniqid()
);
# The SDK throws an exception if a Connect endpoint responds with anything besides
# a 200-level HTTP code. This block catches any exceptions that occur from the request.
try {
$result = $transactions_api->charge($location->getId(), $request_body);
echo "<pre>";
echo "Card has been Approved!";
echo $result['amount'][0];
echo $result['transaction_id'][1];
echo "</pre>";
} catch (\SquareConnect\ApiException $e) {
echo "Caught exception!<br/>";
print_r("<strong>Response body:</strong><br/>");
echo "<pre>"; var_dump($e->getResponseBody()); echo "</pre>";
echo "<br/><strong>Response headers:</strong><br/>";
echo "<pre>"; var_dump($e->getResponseHeaders()); echo "</pre>";
}
Example: I want to write the transaction data to the "transactions" table with the member's ID number and transaction number and if it was approved or declined.
Thank you!!!! I hope what I am attempting to do isn't too complicated.
Try using var_dump() instead of echo if you are having problems displaying things with echo, and you might learn some more info about what object you are using.
Instead of $result['amount'][0] try something like $result->getTransaction()-> getTenders()[0]->getAmountMoney()->getAmount() You aren't seeing anything echo'd because you are trying to print things that don't exist.
Don't forget to check out the documentation as well:https://github.com/square/connect-php-sdk/blob/master/docs/Model/ChargeResponse.md
We need to check the class member variable, if it is a object of any class or just like normal datatype as int, string.
If it is object of other related class, we need to go in this way.
//Last four digits of card
$card_last4 = ($result->getTransaction()->getTenders()[0]->getCardDetails()->getCard()->getLast4());
//Card Brand Like, VISA,AMEX
$card_brand = ($result->getTransaction()->getTenders()[0]->getCardDetails()->getCard()->getCardBrand());
These classes and functions can be found under Models at below path.
\vendor\square\connect\test\Model
Hope this will help!!

Passing variables to fpdf

I have a problem with passing variables to fpdf. First script is getting post text sent to filtering class, the class is returning filtered POST-s as a 2 element array. First script looks like this:
include('service.php');
include('pdf.php');
$pdf_filter = new Pdf_filter;
$filter = $pdf_filter->pdfFilter();
var_dump($filter);
extract($filter);
I'm extracting $filter array to get variables from it (filtering script is creating variables of the POST that are sent and I can echo them so I don't know if this is even necessary).
The second script looks like this:
require('E:\Xampp\php\fpdf181\fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',12);
$pdf->Cell(195,5, $tytul, 0,1,'C');
$pdf->Cell(195,5, $petycja, 0,1,'C');
$pdf->Output();
and I'm getting this error:
Notice: Undefined variable: tytul in E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\pdf.php on line 10
Notice: Undefined variable: petycja in E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\pdf.php on line 11
Fatal error: Uncaught exception 'Exception' with message 'FPDF error: Some data has already been output, can't send PDF file' in E:\Xampp\php\fpdf181\fpdf.php:271
Stack trace: #0 E:\Xampp\php\fpdf181\fpdf.php(1063): FPDF->Error('Some data has a...')
#1 E:\Xampp\php\fpdf181\fpdf.php(999): FPDF->_checkoutput()
#2 E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\pdf.php(12): FPDF->Output()
#3 E:\Xampp\htdocs\php\bazy_danych\obiektowe\my\test.php(3): include('E:\\Xampp\\htdocs...')
#4 {main} thrown in E:\Xampp\php\fpdf181\fpdf.php on line 271
How should I pass the variables? Interesting: it works if I use the unfiltered $_POST with the following code:
require('E:\Xampp\php\fpdf181\fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',12);
$pdf->Cell(195,5, $_POST['tytul'], 0,1,'C');
$pdf->Cell(195,5, $_POST['petycja'], 0,1,'C');
$pdf->Output();
EDIT: I will post the initial form and filtering function:
Form:
<form action="test.php" method="POST">
Wpisz tytuł petycji (35 znaków):<br>
<input type="text" name="tytul" maxlength="35" size="35" placeholder="Tytuł petycji" required><br>
Wpisz treść petycji (500 znaków):<br>
<textarea name="petycja" maxlength="500" rows="4" cols="50" placeholder="Treść petycji" required></textarea><br>
<input type="submit" value="Napisz petycje">
</form>
Filtering function:
class Pdf_filter{
protected $title;
protected $text;
public function pdfFilter(){
if (isset($_POST)){
foreach ($_POST as $key => $val) {
$filterVal = strip_tags($val);
$filterVal = htmlspecialchars($filterVal);
$filterVal = stripslashes($filterVal);
$filterVal = str_replace("\\", "", $filterVal);
$filter = array($key => $filterVal);
foreach ($filter as $key => $val) {
echo "[$$key]";
echo "$val<br>";
${$key} = $val;
}
}
if(!preg_match("/^[\sa-zA-ZĄĆĘŁŃÓŚŹŻąćęłńóśźż0-9-_,.:\'?()]+$/", $tytul)){
echo "Niedozwolone znaki $tytul!";
exit();
}
elseif(!preg_match("/^[\sa-zA-ZĄĆĘŁŃÓŚŹŻąćęłńóśźż0-9-_,.:\'?()]+$/", $petycja)){
echo "Niedozwolone znaki $petycja!";
exit();
}
else{
return $filter = array('tytul'=>$tytul,'petycja'=>$petycja);
}
}
else{
echo "Proszę wypełnić wszytskie pola!";
}
}
}
Well I am dumb. The problem was related with class variables. Code that happened to work for me:
class Pdf extends FPDF{
protected $filter;
protected $tytul;
protected $petycja;
public function __construct($filter){
$this->filter = extract($filter);
$this->tytul = $tytul;
$this->petycja = $petycja;
}
public function tytul(){
return $this->tytul;
}
public function petycja(){
return $this->petycja;
}
public function dokument(){
parent::__construct();
$this->AddPage();
$this->SetFont('Arial','B',15);
$this->Cell(195,5, $this->tytul, 0,1,'C');
$this->Cell(195,5, $this->petycja, 0,1,'C');
$this->Output();
}
}
Now I need to think of a way to display polish symbols in fpdf and line breaks (but that maybe done with text editor isntead of just textbox).

I am stuck, mysqli_query() expects at least 2 parameters

I have a problem with a code in php it shows me this as errors.
register
mysqli_query() expects at least 2 parameters, 1 given in
C:\xampp\htdocs\search_engine\insert.php on line 99
And this is the code :
<?php
$db = new PDO('mysql:host=localhost;dbname=srgn;charset=utf8mb4', 'root', '123456');
if(isset($_POST["submit"]))
{
$s_link = $_POST["s_link"];
$s_key = $_POST["s_key"];
$s_des = $_POST["s_des"];
{
$sql = "insert(site_link, site_key, site_des) values('$s_link', '$s_key', '$s_des')";
$rs = mysqli_query($sql);
if($rs)
{
echo "<script> alert('Site uploaded successfully') </script>";
}
else
{
echo "<script> alert('Uploading failed, please try agin.') </script>";
}
}
}
?>
Where is the error please, and how can I set it?
Pass on the connection link as the first parameter and the SQL query as the second parameter. This is required as you are doing procedural code. Refer to the link below for more details
http://php.net/manual/en/mysqli.query.php

Prepared statement WHERE clause to open a details page

In the main page I want the following link to open a details page:
<td><a href=details.php?c_id=<?php echo $c_id ?> ><img src="./images/<?php echo $row['cfilename']; ?>" width="90" height="120" alt="" /></a></td>
And the details.php code:
<?php
$mysqli = new mysqli("localhost", "joseph", " ", "collectionsdb");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// get value of object id that was sent from address bar
//$c_id = mysql_real_escape_string(c_id);
/* Create the prepared statement */
if ($stmt = $mysqli->prepare("SELECT c_id,ctitle,csubject,creference,cyear,cobjecttype,cmaterial,ctechnic,cwidth,cheight,cperiod,cmarkings,cdescription,csource,cartist,cfilename FROM collections WHERE c_id=$c_id")) {
/* Execute the prepared Statement */
$stmt->execute();
/* Bind results to variables */
$stmt->bind_result($c_id,$ctitle,$csubject,$creference,$cyear,$cobjecttype,$cmaterial,$ctechnic,$cwidth,$cheight,$cperiod,$cmarkings,$cdescription,$csource,$cartist,$cfilename);
/* fetch values */
while ($rows = $stmt->fetch()) {
// display records in a table
// and the table of results
?>
However, when i press the link the details.php opens with all the data. I expect to only open data of a particular $c_id variable. I am not sure why it is not being passed to the details page. In the way I have put the WHERE condition, I am geting an undefined variable error for c_id.
Please,what have I missed?
Joseph
First
$mysqli = new mysqli("localhost", "joseph", " ", "collectionsdb");
You are passing space to db password. Should be
$mysqli = new mysqli("localhost", "joseph", "", "collectionsdb");
Second
Is your global_register directive in php.ini enabled?
If enabled, the variable you have assigned as query string will be passed as $c_id. You can check if register_globals enabled by write php_info() in this page. See here
If not enabled, you need to assign query string variables value to a variable or directly pass the variable to the database.
Style 1:
$c_id = $_GET['c_id'];
$stmt = $mysqli->prepare("SELECT c_id,ctitle,csubject,creference,cyear,cobjecttype,cmaterial,ctechnic,cwidth,cheight,cperiod,cmarkings,cdescription,csource,cartist,cfilename FROM collections WHERE c_id=$c_id"
Style 2:
$stmt = $mysqli->prepare("SELECT c_id,ctitle,csubject,creference,cyear,cobjecttype,cmaterial,ctechnic,cwidth,cheight,cperiod,cmarkings,cdescription,csource,cartist,cfilename FROM collections WHERE c_id=$_GET['c_id']"
Sanitize you value from query string for style 1 & 2.. Hackable. :)
Let register_global directive enabled is not good. Advise, take the value from query string, sanitize it and pass to the query.

How to do mysql_fetch_array in Magento

I want to create a drop down option using Magento module that populate the data from the database I created.
Previously, I have this code in My IndexController.php which is work. This is the first code.
public function dropdownAction() {
if (file_exists('./app/etc/local.xml')) {
$xml = simplexml_load_file('./app/etc/local.xml');
$tblprefix = $xml->global->resources->db->table_prefix;
$dbhost = $xml->global->resources->default_setup->connection->host;
$dbuser = $xml->global->resources->default_setup->connection->username;
$dbpass = $xml->global->resources->default_setup->connection->password;
$dbname = $xml->global->resources->default_setup->connection->dbname;
}
else {
exit('Failed to open ./app/etc/local.xml');
}
$link = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname) or die("Unable to select database");
$tblname = $tblprefix.'my_db_table';
$result = mysql_query("SELECT dropdowndata FROM ".$tblname."");
echo '<select>';
while ($ary = mysql_fetch_array($result)){
echo "<option>" . $ary['dropdowndata '] . "</option>";
}
echo "</select>";
mysql_close($link);
}
But I think the code above is not the Magento way. Do you agree?
Now, I want to populate the data with this code in IndexController.php. This is the second code.
public function dropdownAction() {
$options= Mage::getModel('my/model')->getCollection();
foreach($options as $option){
$optionData = $option->getDropdowndata ();
echo "<select>";
echo "<option>" .$optionData."</option>";
echo "</select>";
}
}
Using the code above, the data was populated but one data with one drop down option. So there are so many drop down options appear on the browser, each drop down option will contain only one data.
I think I am missing the while ($ary = mysql_fetch_array($result)). But I confuse how to include that code?
So, my question is how to do mysql_fetch_array in Magento? Or can somebody please explain how to make the second code above work like the first code.
getData() function returns an array of the whole data, and of course need move 'select' nodes out of the foreach
echo "<select>";
foreach($options as $option){
$optionData = $option->getData();
echo "<option>" .$optionData['somekey'] ."</option>";
}
echo "</select>";
But I think would be better use the magento magic functions, for example if you have 'entity_id' column in DB you can get value using $option->getEntityId(), etc...
And why do you have select inside of foreach? I think something like this will solve your problem:
public function dropdownAction() {
$options= Mage::getModel('my/model')->getCollection();
echo "<select>";
foreach($options as $option){
$optionData = $option->getDropdowndata ();
echo "<option>" .$optionData."</option>";
}
echo "</select>";
}