FAQ Database Discussion Community


Transactions in php function or in mysql stored procedure?

php,mysql,pdo,transactions
What is better way to begin a transaction? Inside procedures or PHP functions? For example I calling MySQL procedure like this: function sendLeaguesToDb(){ $leagues = ""; try{ $this->PDO->beginTransaction(); $stmt = $this->PDO->prepare("call insupd_Leagues(:id,:name,:country,:sport_id,:his_data,:fixtures,:livescore, :numofmatches,:latestmatch)"); $leagues=$this->soccer->GetAllLeagues(); foreach($leagues as $key=>$value){ $stmt->bindParam(':id',$value->Id); $stmt->bindParam(':name',$value->Name);...

using sql LIMIT 1 on specific queries

php,mysql,sql,pdo,limit
I was wondering if is more memory-efficient to include LIMIT 1 on queries when we expect 1 result at all times. So for example I have the following query select * from clients where client_id = x I don't have extensive db management skills but I'm assuming that select...

PDO FETCH_CLASS multiple rows into array of objects

php,arrays,oop,pdo
I'm trying to fetch multiple rows of bookings from a database and I want each one to be an instance of a specific class - so I attempted to store them within a multidimensional array. So far it works in terms of creating the array of objects, however I need...

Insert form value into mysql database with pdo

php,mysql,pdo
Hi I changed my mysql querys into pdo. Now the problem is that I havent any experience with pdo. I edit it how I thought but nothing works. No errors are showing. Can anyone find the mistake? Thanks for reading. <?php session_start(); if(isset($_POST["submit"])){ $hostname='localhost'; $username='root'; $password=''; function generateRandomString($length = 8)...

PHP PDO Class connection

php,pdo
Hello so currently I've downloaded a PHP PDO class and this what it looks like: class db extends PDO { private $error; private $sql; private $bind; private $errorCallbackFunction; private $errorMsgFormat; public function __construct($dsn, $user="", $passwd="") { $options = array( PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); try { parent::__construct($dsn, $user,...

MySQL - PDO - Allow if POSTS are NULL

php,mysql,pdo
If i fill every input in the form, the data will go successfully into the database, but when i don't fill the input telephone, the data will not go to the database and will give a error : error sqlstate 23000 integrity constraint violation 1048 column 'telephone' cannot be null...

PHP PDO What are the difference between exec() and commit()

php,mysql,pdo
Can anyone explain what are the differences between PDO::commit() and PDO::exec() methods in PHP PDO library class. For instance **assume PDO connection was established $pdo = pdo_connection and params $pdo->beginTransaction(); $sql = "INSERT INTO USERS VALUES ('u1','u2')"; $pdo->exec($sql); $pdo->commit(); I want to know which stage data will be saved permanently...

Does testing a PDO query in an if statement also run it?

php,mysql,pdo
I was checking up how to test for query success, and saw this method: if($db->query(...)){ //It was successful! } else { //Something went wrong } But does this only check if the query would run successfully, or does it run the query and then return true/false? I'm assuming it is...

Second Select Query in function not working

php,mysql,pdo
I am trying to execute 2 Select queries, one right after the other. The first query is contained in a function. From within this function another function is called containing the sql statement. At first I tried to add both sql statements into the same function. That did not work...

Something is wrong with my PDO query?

php,mysql,pdo
Okay, so here is a troublesome chunk of a small PHP script I'm trying to write: if (!empty($_POST)) { $pdusername = $_POST['username']; $pdpassword = $_POST['password']; $pdemail = $_POST['email']; $crumbs = '...

php: loading oracle driver gives error “Unable to load dynamic library - The specified procedure could not be found.”

php,oracle,dll,pdo
I seem to have a strange problem with PHP. I've migrated a bunch of software from one server to another. On the server some scripts make a connection to Oracle, so to be able to make a connection the oracle client is installed and a tnsnames file is in place....

PDO bindParam right way? [closed]

php,sql,pdo
Hey a quick little question. What is the better or safest way to bind parameters, values and columns? i'v seen these two ways to do it, but i can't figure out what the difference is? with :email and the :email, $email $stmt = $db->prepare( "SELECT `email` FROM `users` WHERE `email`...

PDO query to display on id information

php,mysql,pdo
I have the following table: tbl_users ============== id username password email I have the following code to get all the id's of the users and i only want to display the id field. But i can't get it to work. $db = $DB_con; $stmt = $db->prepare("SELECT * FROM tbl_users"); $result...

PHP pass value of checkbox to query

php,checkbox,pdo
Hello so I have this form with 3 checkbox: <form action="send.php"> <input type="checkbox" name="txt_group" value="CID">CID <input type="checkbox" name="txt_group" value="OSDS">OSDS <input type="checkbox" name="txt_group" value="SGO">SGO <input type="submit"> </form> And in my send.php I have this code: $stmt = $dbc->query("SELECT * FROM tblcontactlist WHERE contactGroup=:cgroup"); $stmt->bindParam(':cgroup', $_POST['txt_group']); $stmt->execute(); I think that if I...

Proper way to use PDO with mass amount of INSERT Values

php,mysql,post,pdo
I am using PDO to insert into a MySQL DB input from users on a form with 10 input fields. I make a numeric array containing the $_POST values by doing this: foreach ($_POST as $key => $val) { //testInput() sanitizes the input $postArray[] = testInput($val); } From all the...

PDO returns empty array as result

php,mysql,ajax,pdo
I have a simple search form, which I use to send a POST request to my php script using AJAX. I want the script to search my database for the keyword in the title column, and return the rows where it finds it. The posted data looks like this "searchword=test1",...

Create array with key and value in loop PHP

php,arrays,multidimensional-array,pdo
I'm using PDO, and I managed to get the table columns despite the table name and create the bind variables, like in ... VALUES (:foo, :bar);. The method I'm trying to do this is insert(). public function insert() { // the variable names depend on what table is being used...

How to set charset in mssql_connect?

php,pdo,utf-8,character-encoding
I'm using PHP 5.3 on FreeBSD. I want to select some utf-8 data (persian characters) from SQL Server database, and write them to a text file, but because of utf-8 does all the characters will be written to file ????. I have searched for two days and read most of...

Virtual Box MySQL Server VM constantly timing out

php,mysql,laravel,pdo,virtualbox
I'm trying to connect to my MySQL server hosted in a VirtualBox VM with the following configuration file: # # The MySQL database server configuration file. # # You can copy this to one of: # - "/etc/mysql/my.cnf" to set global options, # - "~/.my.cnf" to set user-specific options. #...

Most efficient way to Select all, and to include a distinct column value - while ordering by date added

mysql,pdo,mysqli
Here's the problem. I have rows that get updated automatically. Sometimes rows are updated (via a new insert - an almost duplicate row) where some columns remain the same - and other columns have new values. I want to pull the most recent up to date row; all the values....

php PDO for loop brakes code

php,pdo
The following is part of my PDO script that gets AJAX POST requests from my webpage. So far I've got it working as intented, but now I would like to add a simple for-loop that iterates trough my $results array, and runs strtotime on a timestamp that's under the key...

“Undefined method PDO::execute()” despite using prepare

php,oop,pdo,undefined
This code has been working before, but I recently added a database class. I get the instance and connection from it: $connection = MYSQLDatabase::getInstance()->getConnection(); $connection->prepare("INSERT INTO users etc etc....... $insertArray = $connection->execute(array( ":username" => $_POST["username"] )); getInstance() returns the database instance. getConnection() returns the connection property which contains: new PDO('mysql:host='...

foreach loop with PDO::FETCH_ASSOC, Invalid argument supplied

php,pdo,foreach
I'm quering my database, and want to write a foreach loop, that goes trough my result set, and runs strtotime on the timestamp, in order to use it on my webpage (I want to adjust the array["posted"] value to strtotime(array["posted"]). I am new to php and PDO, and can't figure...

PHP MySQL product data and pagination [closed]

php,mysql,pdo
First e-commerce project I am busy with, and need some assistance please. With previous help from a stackoverflow member I got the following code that worked for me to get product data from the database and display according to template style: <div class="row"> <?php include("_assets/_conn.php"); $sql = "SELECT * FROM...

Variable number of updates to MYSQL database

php,mysql,pdo
I have a PHP page that is interacting with a MYSQL database using PDO. I have a function that updates numerous fields in the database as requested. Since I do not know how many fields will be updated in advance, it is tricky to write a single query. Which of...

PDO-exception for deleting not existing row

php,sql,pdo
In my table id |name 1 | one then $id = '2'; $sql=$this-con->query("delete from aTable WHERE id = '".$id."' " ); the line will just execute with /* Affected rows: 0 Found rows: 0 Warnings: 0 Duration for 1 query: 0.000 sec. */ Even there's is no such id 2...

PDO MSSQL error query on null

php,mysql,sql-server,pdo
I am trying to select rows from my database table, and I am getting an error stating that Fatal error: Call to a member function query() on null in.. Our connection to the database shows successful. Below is my php code: <?php require_once("dbconn.php"); $db = getConnection(); $input_pid = "870104-07-5448"; $sql...

get value from mysql row pdo

php,mysql,pdo
Hi I am a beginner at pdo and try to get a variable from the column code and then check if the variable is has the same value how the inputelement code. Thats the error message: Fatal error: Call to a member function fetchColumn() on string in C:\xampp\htdocs\social\activation1.php on line...

Insert cookies and date pdo mysql

php,mysql,cookies,pdo
I try to insert the 3 cookies and the date with pdo into my database. But I have no idea how I can do that. The input values become inserted in the database. And the cookies are set in a page before. Any hints? <?php $cookie_name = 'longitude'; if(isset($_POST["submit"])){ $hostname='localhost';...

how to print the result of an SQL Query from a PDO Object

php,mysql,pdo
I am using PHP+PDO+MySQL to run some queries. My queries are working fine, but i am not able to print or access the individual rows. Here is the sql query : $sql = "SELECT BUS_ID FROM noname WHERE STAND_ID=:start and BUS_ID in (SELECT BUS_ID FROM noname WHERE STAND_ID=:end)"; When i...

Fetching database records with MySQL - random row selection with PDO

php,mysql,ajax,pdo
I'm trying o fetch data from a database specific to a quiz. I have two tables named 'questions' and 'options'. Each question has 2 corresponding options and 'questionID' row is present in 'options' table as a foreign key. I'm fetching 4 random questions and their corresponding answers with this query:...

why mysql just text type is avaible?

php,mysql,pdo,blob
I was codding with php and use PDO/MySQL to store user uploaded files in DataBase whene I set contents column to TEXT script work successfully but TEXT Type Limit is 64kb and file size is near 700kbs so I wanna to set column type to MEDIUMTEXT or any BLOB types...

Select case insensitive using mysql, php and pdo

php,mysql,pdo
I'm trying to select some data from a mysql table but I cannot get the Where comparison to be case insensitive, I tried using LOWER: $wildcard = $_GET['q']; $query = "SELECT id, name, departamento FROM gestionDoc_cargos WHERE (LOWER(name) LIKE '%' LOWER(:wildcard) '%' OR LOWER(departamento) LIKE '%' LOWER(:wildcard) '%')"; try{ $result...

PHP PDO Class and Smarty

php,pdo,smarty
Hello so currently I am using a php pdo class for my database connection and here is the code class db extends PDO { private $error; private $sql; private $bind; private $errorCallbackFunction; private $errorMsgFormat; public function __construct($dsn='', $user='', $passwd='') { $options = array( PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );...

Can't insert data via PDO using associative array

php,mysql,pdo
That's how I'm trying to do it: database.php: <?php $host = "host"; $user = "user"; $pass = "password"; $dbname = "database"; try { # MySQL with PDO_MYSQL $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch(PDOException $e) { echo $e->getMessage(); } ?> file that must insert data:...

query not selected closest values

mysql,pdo
I think this line: Poscode , ABS( Poscode - :distance ) AS distance in below code,is being ignored: SO it's just taking this line into consideration thus return the exact records for the postcode provided, instead of listing all closest records to the postcode given! $bindings[] = array(":distance", $postcode, PDO::PARAM_STR);...

how to install multiple tables to a mysql database with php pdo

php,mysql,pdo
I am creating a CMS and have created a self installer that creates the tables in the database. I am using this php code which everything works great on wamp but the script quites after 10 files on the server. if (!$db = new PDO('mysql:host='.$dbhost.'; dbname='.$dbname, $dbuser, $dbpass)){$msg = 'e|Could...

PDO Prepared Statements: Replacing the value of a column

php,sql,pdo,prepared-statement
How do you use prepared statements and bound parameters to replace a value in a column? For example, $stmt = "UPDATE users SET name = :name WHERE name = :name"; $stmt->bindParam(:name, $oldName); $stmt->bindParam(:name, $newName); $stmt->execute(); ...

Read array from PDO using FETCH_KEY_PAIR

php,arrays,pdo
I am trying to read the array from the following code. I thought it should be easy but I am struggling. My code pulls back two variables in the array. $stmt5=$mysql_link->prepare("SELECT stationlong AS stationlong,tpl AS tpl FROM station WHERE stationlong=:stationlong LIMIT 1"); $stmt5->execute(array(':stationlong'=>$q)); $stations=$stmt5->fetchAll(PDO::FETCH_KEY_PAIR); var_dump($stations); $stationlongs=$stations[0]; $stationshorts=$stations[1]; An example array...

SELECT within SELECT PDO prepared statement [duplicate]

php,mysql,security,pdo,prepared-statement
This question already has an answer here: Are PDO prepared statements sufficient to prevent SQL injection? 7 answers I'm thinking of an example like this one: The request hits a page at an url (by whichever means), with a parameter. example.com/api/page?name=bob. It's my understanding that you should do a...

PDO: Create dynamic insert syntax error

php,mysql,pdo
I am working on a project that requires me to do a database insert with quite some columns to fill. I tried making my function dynamic so that I didn't have to type 28 insert into- columns, 28 placeholders, and then bind 28 values to 28 placeholders....and in the near...

how to make a link in a mysql result and open a new window when clicked? [duplicate]

php,pdo
This question already has an answer here: how to make a link from the records in mysql? 1 answer I have here the code for making a mysql result a link using a javascript. But my problem is this, when i click that link it opens a new window...

Limit select options

php,mysql,pdo
The other day when I was out with friends it all of a sudden hit me that someone could use Inspect Element and change the NAME of the OPTION in the SELECT tag to whatever they want, it would be stored in my database (still unsure on why I was...

calling PDO with AJAX, returns an empty string

php,mysql,ajax,pdo
I have a simple database query written in PHP using PDO. When I var_dump my $results, I get an associative array. So I figured I'd just use return $ result, call the script using AJAX and then work from there. But now when I console.log the data I get, I...

echo json_encode returns an empty string

php,pdo
I have a php script that runs a simple SELECT query, and it seems to work fine. Here's the script: error_reporting(E_ALL); ini_set('display_errors', 1); try { $hostname = "localhost"; $username = "root"; $password = ""; $db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC;charset=utf8",$username, $password); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); if (!empty($_POST["searchword"])) { $searchword = $_POST["searchword"]; $query = $db->prepare("SELECT...

Having an hard time fetching data from sql query using PHP PDO

php,mysql,pdo
I have a script and connects to a database, then inserts data into a database. However I am having an issue fetching the data. Here is the error message I get: Fatal error: Call to a member function fetchAll() on boolean in C:\xampp\htdocs\projects\forms\db.php on line 24 What am I doing...

PDO Inserts data twice on single query

php,mysql,pdo
I have a terrible problem with pdo statements. My class generate a SQL Query based on the Object, then forward the query and params to Bd Class and execute, but data is inserted twice to database. Table in database CREATE TABLE IF NOT EXISTS `es_simple_object` ( `id_object` int(10) unsigned NOT...

PDO Query fetchAll remove keys but keep values including duplicates

php,mysql,pdo
I am trying to add custom fields to my presentation platform and have the following MySQL/PDO query: SELECT presenters.presenter_name, presenters.presenter_email, presenters.presenter_contact, presentations.presentation_uid, presentations.presentation_presenter_notes, presentations.presentation_date, presentations.presentation_customer_reference, presentations.presentation_customer_name, presentations.presentation_customer_email, customfields.customfield_name, customfields_data.customfield_data_value FROM presentations INNER...

Getting an integer from MySql using php

php,mysql,pdo
I am quite new to php and I have some problems with my final year project at school. I have an issue retrieving an integer from a Select statement using php. I have 2 tables: Table Camping : capacity(int 11) spot_nb (int 11) location (varchar 20) availability (varchar 1) //this...

Pass multiple parameters in PDO

php,mysql,pdo
My PHP looks like this: $diagSel = $_POST['diagSel']; $search_crit = $_POST['criteria']; //this is an entry like "85054,85206" (no quotes) $sql1 = "SELECT * FROM `myTable` where`Diagnosis` = :diagnosis and `zip_code` in (:placeHolder) group by `Provider Number`"; $stmt = $dbh->prepare($sql1); $stmt->bindParam(':diagnosis', $diagSel, PDO::PARAM_STR); $stmt->bindParam(':placeHolder', $search_crit, PDO::PARAM_STR); $stmt->execute(); $result1 = $stmt->fetchAll(PDO::FETCH_ASSOC); header('Content-type:...

Getting data out of a database with XMLHttpRequest, PDO, JSON, PHP and JavaScript

javascript,php,mysql,json,pdo
So following my last question I want to use the value that is submitted in the input tag to get the matching id in my database. I have created two files for it but I cant figure out how to link them. Also note I made a database with a...

Get pdo table information from query with multiple tables

php,mysql,pdo
$lister_query = " SELECT * FROM (SELECT lister1_password lister_password, lister1_status lister_status, lister1_email lister_email FROM lister1 UNION SELECT lister2_password lister_password, lister2_status lister_status, lister2_email lister_email FROM lister2 UNION SELECT lister3_password lister_password, lister3_status lister_status, lister3_email lister_email FROM lister3) AS lister WHERE lister.lister_password = ? AND lister.lister_email = ? "; $lister_prepare = $database_listers ->...

can not insert MCRYPT encrypted data to the database

php,mysql,encryption,pdo,mcrypt
I'm using MCRYPT to encrypt sensitive data and save them to the database. The encrypted data look like this (non-encrypted data above the encrypted data) then insert to the MySQL PDO database as usual in a text field utf8_unicode_ci but the result is empty most of the times. Sometimes it...

Zend Framework 2 - Showing the content of a database

php,mysql,database,pdo,zend-framework2
I'm making some kind of market site with Zend Framework 2. The home got a slider showing all the products (realized with CSS3 keyframes) and some text. Both the sliding pictures and the text are read from a MySQL database. But as result, i get no output but also no...

How to display fetched result inside php form?

php,mysql,pdo
i am a PHP MYSQL beginner! trying to get the id (primary key) value of a row and update its corresponding values in a database. My search results are working perfecting and am getting redirected to my update form page, where in which i wanted to display the fetched result,...

mysql PDO with SELECT OR, Error!: SQLSTATE[HY093]

php,mysql,pdo
I have a simple search form that sends a post request to my php file, that contains the input like this "searchword=test1". I then use that with PDO to search my table for mathing data. So far I was only searching one column, using this statement: $query = $db->prepare("SELECT *...

What is returned from MySQL and pdo::fetchColumn() if an empty result set?

php,mysql,pdo
$sql='SELECT id FROM mytable WHERE x=?'; $stmt=$conn->prepare($sql); $stmt->execute(array(123)); $id=$stmt->fetchColumn(); syslog(LOG_INFO,'id ='.$id.' and is '(is_null($id)?'null':'not null')); PHP $stmt->fetchColumn() returns what appears to be null, however, isn't when tested. MySQL when tested at the shell indicates MySQL returned an empty result set (i.e. zero rows). (Query took 0.0008 sec). What is $stmt->fetchColumn()...

PDO Error: Invalid parameter number: number of bound variables does not match number of tokens

php,pdo
I'm getting the error Invalid parameter number: number of bound variables does not match number of tokens when executing the following code: $query = " SELECT project_id, product_name, product_description, imagelg_url, product_url, amazon_price, your_price, review_value, coupon FROM project WHERE project_id = :id "; $update = " UPDATE project SET product_name =...

PHP PDO data does not inserting [duplicate]

php,mysql,pdo
This question already has an answer here: Syntax error due to using a reserved word as a table or column name in MySQL 1 answer Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the...

CodeIgniter PDO - Call to undefined method CI_DB_pdo_mysql_driver::num_rows()

php,database,codeigniter,pdo
I'm trying to code a web login/registration system and I'm getting the following error: Fatal error: Call to undefined method CI_DB_pdo_mysql_driver::num_rows() in (path to model) on line 7 I tried also using rowCount() instead and it still didn't work. That's the model: <?php class Member_model extends CI_Model { public function...

SQL UNION only returning result from first SELECT

php,mysql,sql,pdo,union
I am attempting to perform a SQL call that fetches a row from one table and counts the records from another table. However, the call only returns results from the first SELECT. Code is as follows: $sql = "SELECT row_1 FROM table_1 WHERE user_id = :user_id UNION SELECT COUNT(row_2) as...

How create a delete using PDO?

pdo
I have a page with with crud function using PDO.my problem is in the delete part what I want is that when I click the "delete" button is should delete it the problem is that when i clicked my delete button nothing is deleting and it redirect me to "delete.php"...

PHP Data Objetcs (PDO) example

php,mysql,oop,pdo
I'm fairly new to object oriented programming in php, I just wrote the following script to create a connection using PDO and run a simple Select Query. It works fine, i just need to know if i have done it right! (need to know the best practices i'm missing). <?php...

Am I safe?? [trying to prevent sql injection] [duplicate]

php,mysql,security,laravel,pdo
This question already has an answer here: How can I prevent SQL-injection in PHP? 28 answers I was wondering if I'm safe from SQL injection if I have this in a script: < script> //some stuff var item = <?php echo json_oncode($PHPVAR) ?> item.replace(/"/,'&quot').replace(/'/,'&#39'); //do more script stuff with...

Multiple queries & LastInsertId

php,mysql,pdo
How wrong is that query? Can I insert multiple queries like that? Can I use lastInsertId like that? $pdo = Database::connect(); $dflt = 'DEFAULT'; $query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo) VALUES (:email, '$hashed_password', :nome, :dt_registo, :tipo, :activo)"; $stmt = $pdo->prepare($query1); $stmt->execute(); $insertedid = $pdo->lastInsertId("utilizador"); $query2 ="INSERT...

Beginner Help: PHP MySQL (PDO) Function

php,mysql,pdo
I am trying to learn PHP and setup a user access based website. I finally found a template that is mostly simple to use and implement. However after hours of struggling to modify the template I have to kindly ask for assistance. The following code works great and I have...

PDO Read From Database

php,pdo
I have made a code using PDO to read a table from a database. I try to echo my result but I get a blank page without error. My Code Is: <?php include 'config.php'; id = "264540733647332"; try { $conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e)...

MYSQL gives same response '0 rows affected' in different situations

php,mysql,pdo
MYSQL update query give same response in different situations "0 rows affected. (Query took 0.0789 sec)" 1) where clause is not matched 2) where clause is matched but the given value is same to the existing value ex: assume that user_id = '86' is not exist in the table UPDATE...

Not able to retrieve a single value from php array

php,arrays,sql-server,pdo
We have a Stored Procedure in MSSQL that returns two values: Agent | Tickets int | int We are successfully connecting to the database server and calling the SP with pdo like this: <?php //Declare hostname variable $hostname = 'servername'; try { $conn = new PDO("sqlsrv:Server=$hostname;Database=dbnamee"); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $agent =...

Looping PHP PDO query result through a function

php,mysql,pdo
I know similar questions have been asked before, but i am not completely satisfied with the answers. Alternatively, I am looking for a better/simpler way to do this. Basically there is a table like this: id object Desc 1 Apple Fruit 2 Orange Fruit 3 cabbage Vegetable A function like...

PDO not being able to return the last_insert_id

php,mysql,pdo,database-administration
<?php session_start(); $userid = $_SESSION['userid']; $categorynumber=0; $categorynumber = create_category($userid); //keep the category number for future reference if($categorynumber > 0){ $_SESSION['categorynumber'] = $categorynumber; } echo $categorynumber; ?> echo $categorynumber prints 0 function create_category($userid) { // connect to database with PDO $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_DATABASE; $dbh = new PDO($dsn, DB_USER, DB_PASSWORD); //...

Add a common word to all json_encode() data

php,mysql,json,pdo
I'm retrieving data from MySQL using json_encode(). $sd=array(); foreach($rslt as $val){ $sd[] = $val; } echo json_encode($sd); My question is How do I add the word "grade" in to all the results? example: if the output is 97 38 73 how do I get the results as: grade97 grade38 grade73...

MYSQL, PHP, PDO Check if row exists [on hold]

php,mysql,pdo
Im trying to check to see if value stored in $steamId is already in the table but its not working. What am i doing wrong. Account_info table +------------+---------+----------+-----+ | Steam_id | Partner | Token | RID | +------------+---------+----------+-----+ | Steamid222 | Part222 | token222 | 1 | +------------+---------+----------+-----+ $stmt =...

SQL checking for NULL fields

php,mysql,database,pdo
SOLVED: I knew there were fields that were empty that should have caught the check, but they were empty rather than NULL. So, when I was checking for NULL fields, it didn't find any. I'm trying to check whether elements in a row with a specific name have any blank...

PDO prepare statment fails

php,mysql,pdo
I have this code to connect mysql on my php file: if (isset($_POST['name'])) { function setPerson($nam, $last_n1,$last_n2, $date_birth) { //We pass all dates of the person include "conexion.php"; $id_family=5; $id_user=1; $query = $conexion->prepare("INSERT INTO person (name, last_name1, birth_date, family_id, user_id) VALUES (name= :nam, last_name1= :last_n1,family_id=:id_family,user_id=:id_user)"); $params = array(":nam"=>$nam,":last_n1"=>$last_n1,":d_b"=>$date_birth,":id_family"=>$id_family,":id_user"=>$id_user);...

Pagination with PDO MySQL Search Multiple Form Fields

php,mysql,search,pdo,pagination
I am having a heck of a time getting this script to work. I have two search fields. That is the reason for the different queries. I can't get the pagination to work with the search script. The pagination alwasy brings back all the records and I get a blank...

MySQL Foreign Key Constraint Fail

php,mysql,pdo,foreign-keys,sql-insert
So, to clarify things: I know why this is failing. The question is: How to work around that? This is my setup: The referencing table is users and the referencing column is id, the referenced table is user_data, and the referenced column is id. I want to store the email,...

PDOException' with message 'SQLSTATE[HY093]

php,mysql,pdo
Error: PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens <?php require '../database.php'; $id = null; if ( !empty($_GET['id'])) { $id = $_REQUEST['id']; } if ( null==$id ) { header("Location: index.php"); } // //echo "<pre>"; //echo print_r($_POST); //echo "</pre>"; // //die(); if...

mysql PHP PDO executing 2 queries on a single POST request

php,mysql,pdo
I'm using a standard apache2 LAMP configuration with mysql and php5, only thing I changed is my character encoding onto UTF8. I'm making an AJAX call upon clicking an anchor (the article title), and want to run 2 queries. One gets the article, and the other the comments related to...

How can I insert a value into the last database entry?

php,mysql,pdo
I have a little tricky code, maybe you have a better solution: What I want to do is, take the "id" of the last inserted entry from the database (1), then put two zeros infront of it (001), take the current "date" and format it (1506) and insert all together...

How can I use MySQL statement 'show index' with PDO?

php,mysql,indexing,pdo,show
I am trying to use PDO and prepared statements to get the primary key of a table. From other questions I saw that this is possible when executing something like this: show index from TABLENAME where Key_name = 'PRIMARY' The problem is that I can not use this from inside...

Laravel 4.2 - Transaction rollback issue with multiple databases

php,laravel,pdo,transactions
I am experiencing issues in rolling back a transaction involving tables from multiple databases. The primary table rollback behaves as expected, but the child row remains, and is now orphaned. public function devUserCreateTest() { DB::beginTransaction(); try { $childUser = new ChildUser; // Exists in database B $parentUser = new User;...

Syntax error sql and save values in array

php,mysql,arrays,pdo
Hi guys I try to create a query with pdo. I want that only the rows are saved in the array $result, that have the value between $lo and $loo or/ and $la and $laa. I´m very new in pdo sorry about the difficult question. Error Message: SQLSTATE[42000]: Syntax error...

Getting a 'Could Not Find Driver' message with new domain name [closed]

php,mysql,pdo,mysqli
I am using a php framework and am successfully using it with the first website I created. I bought a new domain and am working on my second site. The php framework I have is basically for registering/signing in with a lot of other things, but that's the core essentials...

PHP PDO and Mysql [closed]

php,mysql,pdo
<?php // include to get database connection include_once 'config/db.php'; try{ $a_id = "SELECT a.id FROM aluno a, utilizador u WHERE a.utilizador_id = u.id AND u.nome =" . $_POST['nome']; $prof = 1; $query = "INSERT INTO classificacao(nota, semestre, dt_classif, aluno_id, utilizador_id) VALUES (nota=:nota, semestre=:semestre, dt_classif=DEFAULT , aluno_id=:aluno_id, utilizador_id=:utilizador_id)"; $stmt = $con->prepare($query);...

PDO Insert statement not working? [on hold]

php,pdo
I am trying to test out a PDO insert statement and for some really weird reason its not inserting the info and not giving me an error message. I tried running a regular query (with out using prepared statements) and it works.. but this one is not doing any inserts...

Trying to rewrite mysql_* to pdo

php,mysql,pdo
First of all I should say that I started to learn PDO and trying to rewrite some old mine codes. Here is one that I found on tutorial for a jquery/ajax/pdo/mysql comment system which is working. This is the mysql_* part which I'm trying to rewrite -> file submit.php which...

Display MySQL table data in html input field (PDO)

php,mysql,pdo
I want this form to load any data found in the "header" and "summary" columns in my database into the input fields for ease of editing. Then, after the user submits the form, the contents are dumped back into the DB and the new "values" are shown in the form....

Last ID not showing

php,mysql,pdo
I am trying to grab the largest ID number from the database. The output should be 15 but it shows 1. My PHP script: $sql = "SELECT MAX(id) AS id FROM employees"; $sql = $db->prepare($sql); $lid = $sql->execute(); I am outputting it here: <input type="number" name="id" value="<?php echo $lid; ?>"...

$http.get returns actual php script instead of running it (yeoman, grunt)

php,angularjs,pdo,gruntjs
I'm building a "simple" AngularJS app with an articles newsfeed. My articles are stored in a mysql database, and I extract them using php PDO. I used to do this using AJAX with a simple LAMP configuration (php5, mysql, apache2), and everything worked as intended. Now I'm trying to rebuild...

Php and mysql pdo query

php,mysql,pdo
I want to make query to mysql, but when i execute it at end of the page i have needless text. How can i delete it? this is the code: try { //create PDO connection $db = new PDO("mysql:host=".DBHOST.";port=3306;dbname=".DBNAME, DBUSER, DBPASS); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { //show error echo...

SQL Injections PDO Protect

php,mysql,sql-server,pdo
I have one question In my aplication all SQL Queries are with PDO. For Example Notes: <?php include "config.php"; $User_Check = $_SESSION['Login_User']; if ($_SERVER["REQUEST_METHOD"] == "POST") { Notes = $_POST["Notes"]; try { $sql = $conn->prepare('UPDATE Accounts SET Notes = :Notes WHERE Username = :User_Check'); $sql->execute(array('Notes' => $Notes, 'User_Check' => $User_Check));...

I need help using a class in a function in PHP

php,mysql,pdo,mysqli
I'm trying to convert all my mysqli over to PDO, but I'm pretty green with PDO and my problem might be elementary. I'm having trouble with the first query I'm switching over. Here is my setup. In my login.php, I call a function like so: login.php $user = attempt_login($username, $password);...

SQL injection prevention on dynamic parameters

php,mysql,pdo
I have an intresting question: I have a form that is send over GET, and i want to secure the database. Problem is that there are 8 select boxes with arguments that can be passed in the form to the page, but they dont have to be there. I am...

are my conclusion correct about pdo? [closed]

php,mysql,pdo
One: If I use bindParam();, Then execute(); will has no arguments. But if I use a array instead of bindParam(); then execute(); will has argument. something like this: // one $queryResults->bindParam(1,$test); $queryResults->execute(); // two $params = array($mfg, $price); $queryResults->execute($params); Is it right ? Yes or No ? Two: I use...

PHP - PDO connection object query not working

php,mysql,pdo
I'm trying to create a new table with this code: try { $db = new PDO("mysql:hostname=localhost",'root','root'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo $e->getMessage(); die(); } //to create database $db->query("CREATE DATABASE theShop IF NOT EXISTS ;"); $db->query("USE theShop;"); $createTableShops = "CREATE TABLE `advertisor` ( `ShopID` UNSIGNED INT NOT NULL AUTO_INCREMENT...

Using PHP have a MySQL statement into multiple PHP variables

php,mysql,pdo
A little backdrop to what I'm trying to accomplish.. I'm making a simple CMS / blog and I'm trying to have the signature auto created from the database's firstname / lastname values by selecting them by the username.. Then after they are selected I am trying to put them into...

Fail to create array with query values

php,mysql,arrays,pdo
I try to save the query values into an array, but it wont become filled. The query should give something out because any values in the database accomplish the terms and the cookies have too a value. Where is my mistake? Output: Array ( ) $range = 'range'; $_COOKIE["$range"]; $longitude...

Error connecting to MSSQL using PHP

php,sql-server,pdo,odbc,sqlsrv
I am receiving an error as below: PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[08001]: [Microsoft][ODBC Driver 11 for SQL Server]SQL Server Network Interfaces: Connection string is not valid [87]. ' My codes are as follow: $this->link = new PDO( "sqlsrv:server=$this->serverName:$this->port;Database=$this->db", "$this->uid", "$this->pwd" ); I wish someone can enlighten...

PHP hashing prob

php,mysql,pdo
I am doing a Registration / Login and I can't get hashed passwords to match. if(isset($_POST["pass"])) { $pass = $_POST["pass"]; $options = array('cost' => 11); $pass = password_hash("$pass", PASSWORD_BCRYPT, $options)."\n"; } $sql2 = $db->prepare('INSERT INTO Registrace (Email, Password, Nick) VALUES (:email, :password, :nick)'); $sql2->execute(array(':email' => $email,':password' => $pass, ':nick' =>...