Following is the code in my script. the $sql statement is properly working when executed in phpmyadmin. But it dosent work in the following code. displaying only one row of data.
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql="SELECT DISTINCT productId FROM bid WHERE userId =:id";
$st = $conn->prepare( $sql );
$st->bindParam( ":id", $_SESSION['id'], PDO::PARAM_INT );
$st->execute();
$data=$st->fetch(PDO::FETCH_ASSOC);
$conn=null;
print_r($data);
In both methods, replace
$data = $st->fetch(PDO::FETCH_ASSOC);
with the code given.
One of the method would be:
$data = $st->fetchAll(PDO::FETCH_ASSOC);
Loop
while( $data = $st->fetch(PDO::FETCH_ASSOC) )
print_r($data);
$conn=null;
Related
I have the following script which is good IMO for returning many rows from the database because of the "foreach" section.
How do I optimize this, if I know I will always only get 1 row from the database. If I know I will only ever get 1 row from the database, I don't see why I need the foreach loop, but I don't know how to change the code.
$STH = $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH -> fetchAll();
foreach( $result as $row ) {
echo $row["figure"];
}
Just fetch. only gets one row. So no foreach loop needed :D
$row = $STH -> fetch();
example (ty northkildonan):
$id = 4;
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1 ORDER BY x LIMIT 1" );
$STH -> execute();
$result = $STH -> fetch();
echo $result ["figure"];
$DBH = null;
You can use fetch and LIMIT together. LIMIT has the effect that the database returns only one entry so PHP has to handle very less data. With fetch you get the first (and only) result entry from the database reponse.
You can do more optimizing by setting the fetching type, see http://www.php.net/manual/de/pdostatement.fetch.php. If you access it only via column names you need to numbered array.
Be aware of the ORDER clause. Use ORDER or WHERE to get the needed row. Otherwise you will get the first row in the table alle the time.
Did you try:
$DBH = new PDO( "connection string goes here" );
$row = $DBH->query( "select figure from table1" )->fetch();
echo $row["figure"];
$DBH = null;
You could try this for a database SELECT query based on user input using PDO:
$param = $_GET['username'];
$query=$dbh->prepare("SELECT secret FROM users WHERE username=:param");
$query->bindParam(':param', $param);
$query->execute();
$result = $query -> fetch();
print_r($result);
If you want just a single field, you could use fetchColumn instead of fetch - http://www.php.net/manual/en/pdostatement.fetchcolumn.php
how about using limit 0,1 for mysql optimisation
and about your code:
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH ->fetch(PDO::FETCH_ASSOC)
echo $result["figure"];
$DBH = null;
Thanks to Steven's suggestion to use fetchColumn, here's my recommendation to cut short one line from your code.
$DBH = new PDO( "connection string goes here" );
$STH = $DBH->query( "select figure from table1" );
$result = $STH->fetchColumn();
echo $result;
$DBH = null;
I am trying to insert an array of values multiple times into a table.
I have a simple array that is generated by a user checking a box and that's what gets added to the array, I then want to insert each value into a table, I thought I could do it with a foreach loop and iterate $i but it appears I can't, I don't need to worry about security or anything as this is internally used by two people.
here is what I have:
foreach($detailsinvoice as $desc){
$conn3 = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql3 = "INSERT INTO
xero_invoices (ContactName, Description)
VALUES (:ContactName, :Description)";
$st3 = $conn3->prepare ( $sql3 );
$st3->bindValue( ":ContactName", $this->ContactName, PDO::PARAM_STR );
$st3->bindValue( ":Description", $desc, PDO::PARAM_STR );
$st3->execute();
$this->InvoiceNumber = $conn3->lastInsertId();
$conn3 = null;
}
This was my first attempt but gathered that the connection can only be used once then exits, so I tried an iteration but again I learnt that you can't do that with the PDO statement.
$i = 3;
foreach($detailsinvoice as $desc){
$conn[$i] = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql[$i] = "INSERT INTO
xero_invoices (ContactName, Description)
VALUES (:ContactName, :Description)";
$st[$i] = $conn[$i]->prepare ( $sql[$i] );
$st[$i]->bindValue( ":ContactName", $this->ContactName, PDO::PARAM_STR );
$st[$i]->bindValue( ":Description", $desc, PDO::PARAM_STR );
$st[$i]->execute();
$this->InvoiceNumber = $conn[$i]->lastInsertId();
$conn[$i] = null;
$i++;
}
detailsinvoice is the array and the ContactName will be the same each time (the Contactname works just need to figure out looping the array)
I would appreciate if someone could point me in the right direction.
Feature of prepared statements is that you can prepare a statement once and then execute it multiple times, so your code can be rewritten as:
// Create a connection
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "INSERT INTO
xero_invoices (ContactName, Description)
VALUES (:ContactName, :Description)";
// Create a statement
$st = $conn->prepare ($sql);
foreach ($detailsinvoice as $desc) {
// bind values and execute statement in a loop:
$st->bindValue( ":ContactName", $this->ContactName, PDO::PARAM_STR );
$st->bindValue( ":Description", $desc, PDO::PARAM_STR );
$st->execute();
$this->InvoiceNumber = $conn->lastInsertId();
}
// this is optional
$conn = null;
I have no idea where you got the idea a connection can only be used once from. You should connect only once in a script. Then as long as you store and pass around the $conn variable to any functions you may use (Scope of course is relevant here) you can use it as many times as you like.
// connect ONCE per script
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// write the query once
$sql = "INSERT INTO xero_invoices (ContactName, Description)
VALUES (:ContactName, :Description)";
// and prepare it once.
$st = $conn->prepare ( $sql );
// now loop over the array of parameters any number of times you like
foreach($detailsinvoice as $desc){
$st->bindValue( ":ContactName", $this->ContactName, PDO::PARAM_STR );
$st->bindValue( ":Description", $desc, PDO::PARAM_STR );
$st->execute();
// this line looks wrong, as $this->InvoiceNumber will get overwritten
// each time round the loop
//$this->InvoiceNumber = $conn->lastInsertId();
// maybe you ment this, so at least you would have them all????
$this->InvoiceNumber[] = $conn->lastInsertId();
// or I have to assume you are going to add another query HERE
// that will use that ID
}
The concept of a prepared statement is that it is passed to the database, compiled, optimised and saved in the database almost like a stored proceedure.
Once prepared it can be used again and again. All you do is put new values into your parameters each time you execute it.
I'm pretty new to PHP and PDO and I'm trying to make a simple login system. Now, I'm trying to fetch the id and password from my table to compare with the password that the user input(I'm using one way encryption with salt). So, now the problem is, when I do $password = $stmt->fetchColumn(1) only, my login system works. Now when I try to get the id by doing $id = $stmt->fetchColumn(0) just before $password, I cannot login anymore and I get my "Wrong Username/Password" error.
Now I'm pretty sure that I'm doing something wrong with the fetchColumn but I can't figure it out.
Here's a code snippet that works:
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//set how pdo will handle errors
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//this would be our query.
$sql = "SELECT id, password FROM user_admin WHERE email = :email";
//prepare the statements
$stmt = $con->prepare( $sql );
//give value to named parameter :email
$stmt->bindValue( "email", $this->email, PDO::PARAM_STR );
$stmt->execute();
$password = $stmt->fetchColumn(1);
Now the following doesn't work. Notice that this happens when I added the $id:
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//set how pdo will handle errors
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//this would be our query.
$sql = "SELECT id, password FROM user_admin WHERE email = :email";
//prepare the statements
$stmt = $con->prepare( $sql );
//give value to named parameter :email
$stmt->bindValue( "email", $this->email, PDO::PARAM_STR );
$stmt->execute();
$id = $stmt->fetchColumn(0); //That's the problem
$password = $stmt->fetchColumn(1);
Any help is greatly appreciated.
From the documentation:
PDOStatement::fetchColumn — Returns a single column from the next row of a result set
Each time you call fetchColumn it advances to the next row of the result set.
Try using PDOStatement::fetch instead to fetch the entire row as an an array and then accessing the values from there.
$stmt->execute();
$row = $stmt->fetch();
$id = $row[0];
$password = $row[1];
I'm trying to use a LIKE statement to search through a number of columns.
The following code gives the wanted result:
$zoek='%'.$_GET['zoek'].'%';
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//insert the user:
$sql = "SELECT `leerlingnr`,`voornaam`,`achternm_tsnvoegsels`,`klas`
FROM `roosters`
WHERE `leerlingnr` LIKE '$zoek'
OR `voornaam` LIKE '$zoek'
OR `achternm_tsnvoegsels` LIKE '$zoek'
OR `klas` LIKE '$zoek'";
$st = $conn->prepare ( $sql );
$st->execute();
var_dump ( $st -> fetchAll ( ) ) ;
$conn = null;//sluit de connectie
However, when I try to bind the $zoek value, instead of just inserting it in the query, I get 0 results.
$zoek='%'.$_GET['zoek'].'%';
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
//insert the user:
$sql = "SELECT `leerlingnr`,`voornaam`,`achternm_tsnvoegsels`,`klas`
FROM `roosters`
WHERE `leerlingnr` LIKE ':zoekterm1'
OR `voornaam` LIKE ':zoekterm2'
OR `achternm_tsnvoegsels` LIKE ':zoekterm3'
OR `klas` LIKE ':zoekterm4'";
$st = $conn->prepare ( $sql );
$st->bindValue( ':zoekterm1', $zoek, PDO::PARAM_STR);
$st->bindValue( ':zoekterm2', $zoek, PDO::PARAM_STR);
$st->bindValue( ':zoekterm3', $zoek, PDO::PARAM_STR);
$st->bindValue( ':zoekterm4', $zoek, PDO::PARAM_STR);
$st->execute();
var_dump ( $st -> fetchAll ( ) ) ;
$conn = null;//sluit de connectie
After trying for about half an hour (I fixed having % in the query and having only one :zoekterm), I really don't see what I've done wrong.
When binding variables, don't use quotes.
I have the following script which is good IMO for returning many rows from the database because of the "foreach" section.
How do I optimize this, if I know I will always only get 1 row from the database. If I know I will only ever get 1 row from the database, I don't see why I need the foreach loop, but I don't know how to change the code.
$STH = $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH -> fetchAll();
foreach( $result as $row ) {
echo $row["figure"];
}
Just fetch. only gets one row. So no foreach loop needed :D
$row = $STH -> fetch();
example (ty northkildonan):
$id = 4;
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1 ORDER BY x LIMIT 1" );
$STH -> execute();
$result = $STH -> fetch();
echo $result ["figure"];
$DBH = null;
You can use fetch and LIMIT together. LIMIT has the effect that the database returns only one entry so PHP has to handle very less data. With fetch you get the first (and only) result entry from the database reponse.
You can do more optimizing by setting the fetching type, see http://www.php.net/manual/de/pdostatement.fetch.php. If you access it only via column names you need to numbered array.
Be aware of the ORDER clause. Use ORDER or WHERE to get the needed row. Otherwise you will get the first row in the table alle the time.
Did you try:
$DBH = new PDO( "connection string goes here" );
$row = $DBH->query( "select figure from table1" )->fetch();
echo $row["figure"];
$DBH = null;
You could try this for a database SELECT query based on user input using PDO:
$param = $_GET['username'];
$query=$dbh->prepare("SELECT secret FROM users WHERE username=:param");
$query->bindParam(':param', $param);
$query->execute();
$result = $query -> fetch();
print_r($result);
If you want just a single field, you could use fetchColumn instead of fetch - http://www.php.net/manual/en/pdostatement.fetchcolumn.php
how about using limit 0,1 for mysql optimisation
and about your code:
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH ->fetch(PDO::FETCH_ASSOC)
echo $result["figure"];
$DBH = null;
Thanks to Steven's suggestion to use fetchColumn, here's my recommendation to cut short one line from your code.
$DBH = new PDO( "connection string goes here" );
$STH = $DBH->query( "select figure from table1" );
$result = $STH->fetchColumn();
echo $result;
$DBH = null;