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

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

Related

PHP InstanceOf works locally but not on host server

I have an issue with PHP 7's instanceof statement that is only happening on certain conditions.
It seems that instanceof works locally on my dev machine (MAMP Pro running PHP 7.0.13) but not on my Hosted Server (HostEurope, PHP 7).
I have tried the following :
downgrading to PHP 5.6
using is_a instead
Using fully qualified name e.g. \Site\Ad
but they all exhibit the same behaviour.
I've tried Googling "PHP instanceof not working" and variations of it but I haven't found anything relevant.
I was wondering if anyone had experienced something similar or possible solutions to try?
The Code in question is:
<?php
namespace Site;
require_once(__DIR__."/../interface/IOutput.php");
require_once(__DIR__."/../lib/Lib.php");
require_once(__DIR__."/../site/AdMediumRectangle.php");
require_once(__DIR__."/../site/AdSnapBanner.php");
require_once(__DIR__."/../const/Const.php");
class AdFactory
{
/**
* Define(AD_BANNER, 0);
* Define(AD_RECTANGE, 1);
* Define(AD_SUPERBANNER, 2);
* Define(AD_SKYSCRAPER, 3);
**/
/**
* #param $object
* #return AdMediumRectangle|AdSnapBanner|string
*/
public static function CreateObject($object)
{
$ad = wire(pages)->get("/ads/")->children->getRandom();
if ($ad == null)
return new \Exception("No Random Ad found");
switch ($object) {
case AD_BANNER:
echo "AD_Banner Selected\r\n";
$adSnapBanner = new AdSnapBanner($ad);
return $adSnapBanner;
break;
case AD_RECTANGLE:
echo "AD Rectangle Created\r\n";
$adRectangle = new AdMediumRectangle($ad);
return $adRectangle;
break;
case AD_SUPERBANNER:
case AD_SKYSCRAPER:
default:
echo "AdFactory BlankObject created";
return "";
break;
}
}
public static function Markup($object)
{
$obj = AdFactory::CreateObject($object);
if (($obj instanceof AdSnapBanner) || ($obj instanceof AdMediumRectangle)) {
echo "InstanceOf worked";
return $obj->Markup();
}
else {
echo "return blankString";
return "";
}
}
}
Update : This is the code that calls the above AdFactory class
<?php
namespace Site;
require_once(__DIR__."/../interface/IOutput.php");
require_once(__DIR__."/../lib/Lib.php");
require_once(__DIR__."/../factory/AdFactory.php");
require_once (__DIR__."/../const/Const.php");
class AdInjector
{
public static function Inject($page, $ad_pos)
{
//Select an Ad from /Ads/ according to criteria
//$ads = wire(pages)->get("/ads/")->children;
$count = 1; //$ads->count();
if ($count > 0) {
$mod = $page->id % 3;
echo "mod=" . $mod . "\r\n";
if ($mod == $ad_pos) {
switch ($mod) {
case AD_POS_TITLE;
case AD_POS_BANNER:
//Pick an Snap Banner
echo "Banner Injected (banner):" . AD_BANNER . "\r\n";
return AdFactory::Markup(AD_BANNER);
break;
case AD_POS_SIBLINGS:
echo "Banner Injected (rect):" . AD_RECTANGLE . "\r\n";
//Pick an Ad Rectangle
return AdFactory::Markup(AD_RECTANGLE);
break;
default:
return "";
break;
}
} else
return "";
} else
return "";
}
}
instanceof is a language construct which is so essential to PHP that it is de facto impossible not to work properly.
The code you provided is not enough to tell where the issue might be happening.
Chances are, you have a folder not readable on your online server and simply get somewhere a null value instead of an expected object along your code. Ask yourself: "If it is not the object I expect, what else is it?"
Use var_dump() or printf() to investigate what your variables actually contain and you will find the error soon.
For your code, PHPUnit tests would be a benefit, or at least the use of assert() here and there in your code.
Turns out there was a bug in 1 of the API calls I was making to the Processwire CMS.
$ad = wire(pages)->get("/ads/")->children->getRandom();
And my local and server instance of Processwire was not the same version, which was news to me. I normally have it synchronised, including any modules I use.
I also suspect my null check is not correct PHP, to add to the problem.
It has to do with namespaces used in the code:
Locally (Code with no namespaces) I used this, working fine:
if ($xmlornot instanceof SimpleXMLElement) { }
But on the server (code with namespaces) only this worked:
if ($xmlornot instanceof \SimpleXMLElement) { }
See also this question/answer: instanceof operator returns false for true condition

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

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
}

i am having a issue with json codeigniter rest its not closing the tag

i am having a problem with json codeigniter rest
i am making this call to the server and the problem its that its not closing the json tags
s, USA","clientUID":"7","email":null,"idipad":"2","dateModified":null},{"id":"19","uid":null,"name":"Wayne Corporation, Inc.","phone":"932345324","address":"Second st. 312, Gotham City","clientUID":"7","email":"waynecorp#gmail.com","idipad":"1","dateModified":null}]
its missing the final }
this is the code that creates the response :
$this->response(array('login'=>'login success!','user_admin_id'=>$user_id,'client'=>$client,'users'=>$users,'projects'=>$projects,'plans'=>$plans,'meetings'=>$meetings,'demands'=>$demands,'tasks'=>$tasks,'presences'=>$presences,'contractors'=>$contractors,'companies'=>$companies), 200);
this is the client call using curl :
$this->curl->create('http://dev.onplans.ch/onplans/index.php/api/example/login/format/json');
// Option & Options
$this->curl->option(CURLOPT_BUFFERSIZE, 10);
$this->curl->options(array(CURLOPT_BUFFERSIZE => 10));
// More human looking options
$this->curl->option('buffersize', 10);
// Login to HTTP user authentication
$this->curl->http_login('admin', '1234');
// Post - If you do not use post, it will just run a GET request
//$post = array('remember'=>'true','email'=>'admin.architect#onplans.ch','password'=>'password');
$post = array('remember'=>'true','email'=>'admin.architect#onplans.ch','password'=>'password');
$this->curl->post($post);
// Cookies - If you do not use post, it will just run a GET request
$vars = array('remember'=>'true','email'=>'manuel#ffff.com','password'=>'password');
$this->curl->set_cookies($vars);
// Proxy - Request the page through a proxy server
// Port is optional, defaults to 80
//$this->curl->proxy('http://example.com', 1080);
//$this->curl->proxy('http://example.com');
// Proxy login
//$this->curl->proxy_login('username', 'password');
// Execute - returns responce
echo $this->curl->execute();
// Debug data ------------------------------------------------
// Errors
$this->curl->error_code; // int
$this->curl->error_string;
print_r('error :::::LOGINN REMOTE:::::'.$this->curl->error_string);
// Information
$this->curl->info; // array
print_r('info :::::::::::::'.$this->curl->info);
the response belong to the rest api codeigniter from phil
/**
* Response
*
* Takes pure data and optionally a status code, then creates the response.
*
* #param array $data
* #param null|int $http_code
*/
public function response($data = array(), $http_code = null)
{
global $CFG;
// If data is empty and not code provide, error and bail
if (empty($data) && $http_code === null)
{
$http_code = 404;
// create the output variable here in the case of $this->response(array());
$output = NULL;
}
// If data is empty but http code provided, keep the output empty
else if (empty($data) && is_numeric($http_code))
{
$output = NULL;
}
// Otherwise (if no data but 200 provided) or some data, carry on camping!
else
{
// Is compression requested?
if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE)
{
if (extension_loaded('zlib'))
{
if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
{
ob_start('ob_gzhandler');
}
}
}
is_numeric($http_code) OR $http_code = 200;
// If the format method exists, call and return the output in that format
if (method_exists($this, '_format_'.$this->response->format))
{
// Set the correct format header
header('Content-Type: '.$this->_supported_formats[$this->response->format]);
$output = $this->{'_format_'.$this->response->format}($data);
}
// If the format method exists, call and return the output in that format
elseif (method_exists($this->format, 'to_'.$this->response->format))
{
// Set the correct format header
header('Content-Type: '.$this->_supported_formats[$this->response->format]);
$output = $this->format->factory($data)->{'to_'.$this->response->format}();
}
// Format not supported, output directly
else
{
$output = $data;
}
}
header('HTTP/1.1: ' . $http_code);
header('Status: ' . $http_code);
// If zlib.output_compression is enabled it will compress the output,
// but it will not modify the content-length header to compensate for
// the reduction, causing the browser to hang waiting for more data.
// We'll just skip content-length in those cases.
if ( ! $this->_zlib_oc && ! $CFG->item('compress_output'))
{
header('Content-Length: ' . strlen($output));
}
exit($output);
}
This answer was referenced from Github issue. Also raised by Pedro Dinis, i guest.
I met this problem today and take me long hours to search for the solution. I share here with hope to help someone like me.
The key is to replace around line 430 in the library file: REST_Controller.php :
header('Content-Length: ' . strlen($output));
by
header('Content-Length: ' . strlen("'".$output."'"));
UPDATE: The problem was solved here
Or you can just comment out the code, it will run fine. :)

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

PHP parse error and error code spilling into other pages [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
ok im getting this parse error on my on my login.php page. It seems the code isn't taking into account to check if the user is already logged in. I have a file called pagechecker.php on each page that checks if there logged in but all its showing is php code on top of each page.
Error on login.php is:
Parse error: syntax error, unexpected '(', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in C:\inetpub\wwwroot\OTLCoding\PHP\login.php on line 21
base.php
<?php
session_start();
$dbhost = "localhost";
$dbname = "login";
$dbuser = "root";
$dbpass = "DirectedStudies2012";
$mysqli = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
?>
login.php
<?php
include ("base.php");
include ("passwordchecker.php");
include ("functions.php");
include("pagechecker.php");
function postInput($htmlName)
{
if(isset($_POST[$htmlName]))
{
return $_POST[$htmlName];
}
return null;
}
//check if the user is already login.
if(isset($_SESSION['userid']))
{
//check the database for existing user.
$usercheck->$mysqli->("SELECT * FROM user WHERE userid = ?");
$usercheck->bind_param("i",$_SESSION['userid']);
$usercheck->execute();
$usercheck->store_result();
$results = $usercheck->num_rows;
if($results == 1)
{
redirect("languages.php");
}
}
$loginusername = postInput('username');
$loginpassword = postInput('password');
if(isset($_POST['submit']))
{
if($loginusername == "" || $loginpassword == "")
{
$error = "Please Enter your user name and password";
}
else
{
//user isnt logged in
if($stmt = $mysqli->prepare("SELECT userid, password FROM user WHERE username = ? LIMIT 1"))
{
$stmt->bind_param("s",$loginusername);
$stmt->execute();
$stmt->bind_result($userid,$correctHash);
$stmt->fetch();
if(ValidatePassword($loginpassword,$correctHash))
{
$_SESSION['userid'] = $userid;
redirect('languages.php')
}
$stmt->close();
}
}
}
}
?>
pagechecker.php
//used to check for already login.
if(!isset($_SESSION['userid']))
{
header("Location: login.php");
}
else
{
$usercheck->$mysqli->("SELECT * FROM user WHERE userid = ?")
$usercheck->bind_param("i",$_SESSION['userid']);
$usercheck->execute();
$usercheck->store_result();
$results = $usercheck->num_rows;
if($results == 0)
{
header("Location: login.php");
}
}
The problem is located here:
...->$mysqli->(...
You should call it like that:
...->$mysqli(...
or like that:
...->mysqli(...
depending whether $mysqli is set or not.
Explanation is simple. You can call something like (see more on this in the docs):
$my_object->$my_variable_property_name('some argument');
but calling the arrow between property name and bracket is in fact a syntax error.
Missing semicolon here:
$_SESSION['userid'] = $userid;
redirect('languages.php')
$usercheck->$mysqli->("SELECT * FROM user WHERE userid = ?");
^----
This should probably be
$usercheck->mysqli->etc....