PHP Query Where and Like - php

I try to use a system with jQuery autocomplete to provide a listview
Here is my PHP code, except I can not find the problem, I have no error in the console but I can not seem to get the data that are in the db. It finds me no correspondence.
Conditions "where" are all right and checked (I even try the SQL query directly into phpMyAdmin, and it works, but not through the php file)
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=schoolby_fr', '*****', '*****');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$term = "Malrau";
$pays = "France";
$dept = "Vosges";
$tipe = "Lycée";
$requete = $bdd->prepare('SELECT * FROM school WHERE s_pays="'.$pays.'" AND s_dept="'.$dept.'" AND s_type="'.$tipe.'" AND s_ecole LIKE :term');
$requete->execute(array('term' => '%'.$term.'%'));
$array = array();
while($donnee = $requete->fetch())
{
array_push($array, $donnee['s_ecole']);
}
echo json_encode($array);
?>
EDIT 22/09/2014
I wanted to show you what I get if I voluntarily recalling the condition $pays and $tipe but leaving $term and $dept.
Because it does not work with all conditions.

if you simplify your prepare statement by taking out the variables and hard coding the values maybe you can identify if it's the variables

You should prepare the query the right way, no need for the loop, and always turn on error mode.
<?php
try{
$bdd = new PDO('mysql:host=localhost;dbname=schoolby_fr', '*****', '*****');
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$term = "Malrau";
$pays = "France";
$dept = "Vosges";
$tipe = "Lycée";
$query = 'SELECT *
FROM school
WHERE s_pays= :pays
AND s_dept= :dept
AND s_type= :tipe
AND s_ecole LIKE :term';
$requete = $bdd->prepare($query);
$requete->execute(array(':pays' => $pays,
':dept' => $dept,
':tipe' => $tipe,
':term' => '%'.$term.'%',
));
$donnees = $requete->fetchAll();
//var_dump($donnees);
echo json_encode($array);
}
catch (PDOException $e){
die('Erreur : ' . $e->getMessage());
}

Related

php/pdo insert into database mssql with arrays

I need some help
Is there a way to make this in PDO? https://stackoverflow.com/a/1899508/6208408
Yes I know I could change to mysql but I use a mssql server and can't use mysql. I tried some things but I'm not as good with PDO as mysql... It's hard to find some good examples of inserting array's into database with PDO. So quickly said I have a PDO based code connected to a mssql webserver.
best regards joep
I tried this before:
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$data = array_merge($mon_barcode, $mon_merk, $mon_type, $mon_inch, $mon_a_date, $mon_a_prijs);
try{
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
$insertData = array();
foreach($_POST['mon_barcode'] as $i => $barcode)
{
$insertData[] = $barcode;
}
if (!empty($insertData))
{
implode(', ', $insertData);
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
The code below should fix your problems.
$db_username='';
$db_password='';
$conn = new \PDO("sqlsrv:Server=localhost,1521;Database=testdb", $db_username, $db_password,[]);
//above added per #YourCommonSense's request to provide a complete example to a code fragment
if (isset($_POST['com_id'])) { //was com_id posted?
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
try {
$stmt = $conn->prepare($sql);
foreach ($mon_barcode as $i => $barcode) {
$stmt->execute([$com_id, $barcode, $mon_merk[$i], $mon_type[$i], $mon_inch[$i], $mon_a_date[$i], $mon_a_prijs[$i]]);
}
} catch (\PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;

pdo statement to return more than 1 column in php

I am trying to fetch values from a mysql query using PDO...it works with one column but I need to return 2 columns from the query. Below is the piece of code I have made...
try {
$conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $conn->prepare("select distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%'");
$sth->execute();
$urlsku = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
$urlean = $sth->fetchAll(PDO::FETCH_COLUMN, 1);
echo $sku;
echo $urlsku;
echo $urlean;
It returns me some array values...which I really can't figure out. Can anyone please help me with this.
If you use fetch() with the PDO::FETCH_ASSOC style it is easy to get both columns:
while($row = $sth->fetch(PDO::FETCH_ASSOC) {
echo $row['prod_url'];
echo $row['ean'];
}
By placing the fetch in a loop all of the rows will be returned which you can then limit as you see fit.
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $data[0]['prod_url'];
echo $data[0]['ean'];
Add LIMIT 2 in the query , to get two sets of result :)
try {
$conn = new PDO('mysql:host=localhost;dbname=****', 'root', '****'>setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $conn->prepare("select distinct prod_url,ean from tab_nl where ean in (select ean1 from test_sku where sku='$sku') and prod_url like '%prijzen%' LIMIT 2");
$sth->execute();
$urlsku = $sth->fetchAll(PDO::FETCH_ASSOC, 0);
$urlean = $sth->fetchAll(PDO::FETCH_ASSOC, 1);
print_r($urlsku);
print_r($urlean);

PHP :: Stumped on how to reference specific row in a mysql select array...?

I am just not making a connection here, and im not getting search results that are helping me enlighten myself.
I am pulling data from mysql into an array. But I am tottaly missing how I reference a specific row later.
try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));
foreach($chamberstate as $row) {
$chamber = $row['Chamber'];
$schedule = $row['Schedule'];
$runningnow = $row['RunningNow'];
$temp = $row['ChangingTemp'];
$array = array($chamber,$schedule,$runningnow,$temp);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
Ok, so all the data is in the array. But how do I , say, print the $schedule where $chamber == 1 ?
I feel so dumb for not getting this.....
You were close with your original code but the $array variable was being overwritten each time through the loop. If you need to access the values throughout your page ou should be able to do so with an approach like this.
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));
/* Populate this array for later use */
$chambers=array();
foreach( $chamberstate as $row ) {
$chamber = $row['Chamber'];
$schedule = $row['Schedule'];
$runningnow = $row['RunningNow'];
$temp = $row['ChangingTemp'];
/* This will overwrite any values in the $array variable with each iteration through the loop */
/*
$array = array( $chamber, $schedule, $runningnow, $temp );
*/
$chambers[]=array( 'chamber'=>$chamber, 'schedule'=>$schedule, 'running'=>$runningnow, 'temp'=>$temp );
}
/* later, when you need to access the various values, you can reference via the index */
echo $chambers[ 1 ]['chamber'];
/* or */
echo $chambers[ 23 ]['schedule'];
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));
$caray = array();
foreach($chamberstate as $row) {
$caray[$row['Chamber']]['Chamber'] = $row['Chamber'];
$caray[$row['Chamber']]['Schedule'] = $row['Schedule'];
$caray[$row['Chamber']]['RunningNow'] = $row['RunningNow'];
$caray[$row['Chamber']]['ChangingTemp'] = $row['ChangingTemp'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
print_r($carray['1']);
?>

PHP PDO query on MySQL does not return as expected

I've been working on an iOS web service using PHP, but I'm not having very much luck. I'm attempting to safely query the database and select the id of the user when the name and password match. Unfortunatly, nothing is showing up on the page. I would assume that means the query went wrong somewhere. I've attempted using static values, but to no avail. Any ideas?
P.S. I'm positive the values are correct.
P.P.S. Yes, I know, encrypt. For the simplicity, I'm not bothering.
error_reporting(E_ALL);
ini_set('display errors', 1);
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row = $STH->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($row);
Try it ,
try {
$DBH = new PDO("mysql:host='localhost';dbname='login_test'", 'test', 'development');
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo /*here*/ $e->getMessage();
}
$data = array($_GET['name'], $_GET['password']);
$STH = $DBH->prepare('SELECT id FROM users WHERE name = ? AND password = ?');
$STH->execute($data);
$row =$STH->fetch(PDO::FETCH_ASSOC)
print '<pre>';
print_r($row);

How to echo a specific data from an array in php?

I want to take a specific from an array I have created.
Here's the code:
try
{
// Conecting to MySQL
$bdd = new PDO('mysql:host=localhost;dbname=horse', 'root', '');
}
catch(Exception $e)
{
// ERROR MESSAGE
die('Erreur : '.$e->getMessage());
}
// Fetching the data from the table
$reponse = $bdd->query('SELECT * FROM videos');
$vidarray = array();
while ($donnees = $reponse->fetch())
{
$videolink = $donnees['link'];
$vidarray = array($videolink);
print_r($vidarray);
}
echo $vidarray[1]);
$reponse->closeCursor(); // Closing the request
I want to echo one of these specific data like this
echo $array[1];
I want this to output "WubVcOaW-qs" with this.
I am relativly new to php and I am sure this is pretty basic but can't find it anywhere.
Thanks,
$array = array(
'S01tE08GSNg',
'WubVcOaW-qs',
'2n0ag4qmG5g',
'ni1UR-lXiZo',
'ynvz8P_aFwk'
);
echo $array[1];

Categories