Delete multiple value from database - mysql

I am using this file to delete record from server
<?php
$dbhandle = mysql_connect("localhost", "admin", "admin") or die(mysql_error()) ;
$selected = mysql_select_db("dbname" ,$dbhandle) or die(mysql_error()) ;
$id=$_POST['id'];
foreach($id as $value)
{
$query = mysql_query("DELETE FROM `record` WHERE `id`=$value");
}
mysql_close($dbhandle);
?>
but i am unable to delete record from the database. query is executing without any error but it cannot delete records from table

$query = mysql_query('DELETE FROM `record` WHERE `id` IN (' . implode(',', array_map('intval', $id)) . ')');

This will work even if $id array doesn't contain integers.
class db {
private static $instance = NULL;
private function __construct() {} //Make private
private function __clone(){} //Make private
public static function db() //Get instance of DB
{
if (!self::$instance)
{
self::$instance = new PDO("mysql:host=localhost;dbname=myDB;charset=utf8",'myUsername','myPassword',array(PDO::ATTR_EMULATE_PREPARES=>false,PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true,PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC));
}
return self::$instance;
}
}
if(count($ids)) { //Make sure you don't have an empty data set.
$qMarks = str_repeat('?,', count($ids)-1) . '?';
$sql ="DELETE FROM `record` WHERE `id` IN ({$qMarks})";
$stmt = $db::db->prepare($sql);
$stmt->execute($id);
}

Related

Getting SQLSTATE[HY093]: Invalid parameter number: no parameters were bound in E:\wamp64\www\social\classes\db.php on line 12 error

I'm making a social network's login page but when I login a get the error above. My db.php is (i use pdo):
<?php
class DB {
private static function connect() {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=social;charset=utf8', 'danny', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
?>
Called from
$user_id = DB::query('SELECT id
FROM users
WHERE email=:email')[0]['id'];
DB::query('INSERT INTO login_tokens
VALUES(\'\', :token, :user_id)',
array(':token'=>sha1($token), ':user_id'=>$user_id));
Your class has many issues. to fix them:
class DB {
protected static $pdo;
public static function connect() {
static::$pdo = new PDO('mysql:host=127.0.0.1;dbname=social;charset=utf8', 'danny', 'Dani2034');
static::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function query($query, $params = array()) {
$statement = self::$pdo->prepare($query);
$statement->execute($params);
return $statement;
}
}
DB::connect(); // called only once
$user_id = DB::query('SELECT id FROM users WHERE email=?', array($email))->fetchColumn();
DB::query('INSERT INTO login_tokens VALUES(null, ?, ?)', array(sha1($token), $user_id));

Laravel saves child record, but sets foreign key to null

This has got to be a simple fix, as I have done this many times before. But as it stands I am completely stumped. I use the following code to save a parent object Unknown_Tag and its many children.
Method:
public function saveUnknown(Request $request)
{
$url = $request->url;
$tag = new Unknown_Tag();
$tag->url = $url;
$protocol =
substr($url, 0, strpos($url, ':'));
$tag->protocol = $protocol;
$domain =
parse_url($url, PHP_URL_HOST);
$tag->domain = $domain;
$tag->save();
//get the path
$Path = parse_url($url, PHP_URL_PATH);
if ($Path) {
$splitPath = substr($Path, 1);
$paths = explode('/', $splitPath);
foreach ($paths as $p) {
$path = new Path();
$path->path = $p;
$tag->Paths()->save($path);
}
}
//get Queries
$splitQuery = parse_url($url, PHP_URL_QUERY);
if ($splitQuery) {
$queries = explode('&', $splitQuery);
foreach ($queries as $q) {
$query = new Query();
$q = substr($q, 0, strpos($q, '='));
IF (SUBSTR($q, -1) != ' ') {
$q .= ' ';
}
$query->var = $q;
$value = $q = preg_replace('/^[^=]*:/', '', $q);
$query->value = $value;
$tag->Queries()->save($query);
}
}
}
The Parent Object
class Unknown_Tag extends Model
{
protected $table = 'unknown_tags';
public $timestamps = false;
public function Paths()
{
return $this->hasMany('App\Path', 'tag_id', 'ID');
}
public function Queries()
{
return $this->hasMany('App\Query', 'tag_id', 'ID');
}
}
The Child objects
class Query extends Model
{
protected $table = 'queries';
public $timestamps = false;
public function Tag()
{
return $this->belongsTo('App\Unknown_Tag', 'tag_id', 'ID');
}
}
class Path extends Model
{
protected $table = 'paths';
public $timestamps = false;
public function Tag()
{
return $this->belongsTo('App\Unknown_Tag', 'tag_id', 'ID');
}
}
When I run all this via a post request, The Parent and all the children are saved properly, but all the child objects have a foreign key that is set to null. If I manually change the foreign key to what it should be, everything works just fine, so I am fairly sure this is not a problem with my database. Can anyone see the obvious that I am missing here?
EDIT:Just to be clear, this returns no errors
If anyone ever sees this, laravel assumes the default primary key is 'id'. I had set mine to 'ID', so I had to let laravel know by using
protected $primaryKey = 'ID';
in my Unknown_tag definition

PDO 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I see many have had this same message for a number of different reasons but cannot see any solutions that seem to relate to my specific situation, which on the face of it a very simple one. Yes my password etc is md5 and should be changed but I do not believe that is the issue here.
I would appreciate someone pointing out why the first single line code works and the second does not. There is only one line that meets the criteria in the table in each case.
<?php
// Include database class
include 'DBClass.php';
// Instantiate database.
$db = new DBClass();
//***********************
// This works
//***********************
$em = 'admin#infin8integr8.com';
$sid = 39;
$db->query("select ufname,ulname from users where uemail = :em and sub_id = :sb");
$db->bind(':em', $em);
$db->bind(':sb', $sid);
$row = $db->single();
echo $row['ufname'].' '.$row['ulname'].'<br>';
//***************************
// This returns the error 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in C:\wamp\www\pdo\DBClass.php on line 85
//*****************************
//Line 85 in DBClass is "return $this->stmt->execute();" in
//public function execute(){
//return $this->stmt->execute();
//}
$userid = 'f534983b255eb2820bf3ba1438ddcf65';
$password = '0bfd2660362f242169d11e33f7affe0a';
$db->query = ("select ufname,ulname from users where username = :vuid and upwd = :vpwd");
$db->bind(':vuid', $userid);
$db->bind(':vpwd', $password);
$row = $db->single();
echo $row['ufname'].' * '.$row['ulname'].'<br>';
?>
The relevant class code is:-
<?php
class DBClass{
private $host = 'localhost';
private $user = '<user>';
private $pass = '<password>';
private $dbname = 'infinint_infin8';
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
}
?>

how to group the functions in class

i am new to PHP how to group functions inside a class and use it in other pages to reduce typing this is for single page what if i use multiple pages with pageination
this is my coding
<?php
include ('conn.php');
class sel
{
function sell()
{
if(isset($_POST['submit']))
{
$id=$_POST['id'];
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$result = $myDBObject -> select('*', 'admin', 'username = "'.$username.'" and
password ="'.$password.'"');
$x = $rdata['id'];
echo $x;
$_SESSION['username'] =$id;
echo $_SESSION['username'];
if(! $rdata)
{
echo "Enter your username and password correctly";
}
else
{
echo '<script type="text/javascript">
document.location="list.php";
</script>';
}
}
}
}
$myDBObject = new sel();
$myDBObject->sell();
?>
and my connection.php code is
<?php
class DBConnect
{
private $host = 'localhost';
private $user = 'root';
private $pass = '';
private $db = 'enquiry';
public function __construct(){
$conn = mysql_connect($this -> host, $this -> user, $this -> pass);
$sql = mysql_select_db($this -> db, $conn) or die(mysql_error());
}
private function select($select, $table, $where){
$sql = "select ".$select." from ".$table." where ".$where;
$result = mysql_query($sql);
return $rdata = mysql_fetch_array($result);
}
}
$myDBObject = new DBConnect();
$myDBObject->__construct();
$myDBObject->select($select, $table, $where);
?>
if i did like this i get this error what did i do wrong in code
Fatal error: Call to private method DBConnect::select() from context '' in C:\xampp\htdocs
\Raj\cform\conn.php on line 23
You can use database class as mentioned below
class DBConnect
{
private $host = 'localhost';
private $user = 'user';
private $pass = 'pass';
private $db = 'mydb';
public function __construct(){
$conn = mysql_connect($this -> host, $this -> user, $this -> pass);
$sql = mysql_select_db($this -> db, $conn) or die(mysql_error());
}
// select query
private function select($select, $table, $where){
$sql = "select ".$select." from ".$table." where ".$where;
$result = mysql_query($sql);
return $rdata = mysql_fetch_array($result);
}
// update query
private function update($update, $table, $where){
// code here
}
}
When required, create object of the class and call functions as below
require 'dbConnect.php'; // assuming, you have included the database class in this file
$myDBObject = new DBConnect();
$username = mysql_real_escape_string($_POST['username']); // mysql escaping
$password = mysql_real_escape_string($_POST['password']); // mysql escaping
// select required data
$result = $myDBObject -> select('*', 'admin', 'username = "'.$username.'" and password = "'.$password.'"');
The function described in the class above are for demonstration purpose. You can include other functions in the class along with data escaping functionality.
FYI: mysql is deprecrated. Use mysqli or PDO instead. The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
// Hi,
class ClassName {
static function funcName1(){
funcBody1;
}
static function funcName2(){
funcBody2;
}
}
// to use functions juste do :
ClasseName::funcName1();
ClasseName::funcName2();

AMFPHP complex sql Internal Server Error gateway.php

OK, I am new to AMFPHP. I can do simple sql statements with no problem.
Here are my classes of Schools and Locations:
class Schools {
public $id;
public $district_id;
public $school_name;
// explicit actionscript class
var $_explicitType = "components.Schools";
}
class Locations {
public $id;
public $school_id;
public $school_address;
public $icon_id;
// explicit actionscript class
var $_explicitType = "components.Locations";
}
This simple sql statement works with no issues:
/**
* Retrieves schools data
* #returns id, district_id, school_name
*/
public function getSchools() {
//connect to the database.
$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME);
//retrieve all rows
$query = "SELECT * FROM schools ORDER BY school_name";
$result = mysql_query($query);
$ret = array();
while ($row = mysql_fetch_object($result)) {
$tmp = new Schools();
$tmp->id = $row->id;
$tmp->district_id = $row->district_id;
$tmp->school_name = $row->school_name;
$ret[] = $tmp;
}
mysql_free_result($result);
return $ret;
}
However, I am having a hard time making a "somewhat" complex sql statement work properly.
/**
* Retrieves schools with locations data
* #returns school_name, school_address
*/
public function getSchoolsLocations() {
//connect to the database.
$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME);
//retrieve all schools with their locations
$query = "SELECT schools.school_name AS SNAME, school_address AS SLOC FROM schools, locations WHERE schools.id = locations.school_id";
$result = mysql_query($query);
$ret = array();
while ($row = mysql_fetch_object($result)) {
$tmp = new Schools();
$tmp->id = $row->id;
$tmp->school_name = $row->SNAME;
$ret[] = $tmp;
$tmp2 = new Locations();
$tmp2->school_id = $row->school_id;
$tmp2->school_address = $row->SLOC;
$ret2[] = $tmp2;
array_splice($ret, count($ret), 0, $ret2);
}
mysql_free_result($result);
return $ret;
}
BTW, SELECT schools.school_name AS SNAME, school_address AS SLOC FROM schools, locations WHERE schools.id = locations.school_id works perfectly in mysql.
It doesn't look like you are declaring $ret2.
FWIW: you might get better performance with your query if you format it as a join. Just a thought.