How to echo a specific data from an array in php? - 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];

Related

Issue Undefined variable after storing mysql query into a php variable

I have an issue on my php script. I am trying to store mysql query into a php variable and then I convert the result to string. It seems doing the job in the loop but at the end of my script, I have an error:
Internal Error -
Notice:Undefined variable: result
I want to pass the whole content of the variable $data.
Do you know what i am doing wrong?
Here my php script:
<?php
if (isset($_GET['data']) && $_GET['data']) {
$SelectDataFromRunTable="Select Reference, Variant, HGVSVar FROM run29012016";
$QueryResult=mysqli_query($conn,$SelectDataFromRunTable);
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH)){
print_r($data);
$data=implode(" ",$data);
}//end of while
$NameChecker='astringtest';
$options = array('features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new SoapClient($URL, $options);
try {
$result = $client->submitBatchJob(array('data'=>$data, 'process'=>$NameChecker))
->submitBatchJobResult;
} catch (Exception $e) {
echo $e->getMessage();
}
print_r($result);
mysqli_close($conn);
}
?>
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH)){
$data = implode(" ",$data);
}
This can not work, as you overriding $data with every loop:
while($data = mysqli_fetch_array(...)) will evaluate as many times you have rows in your dataset, till the end. The last assignmet is $data = null (e.g. when you reached the end of you result set) and you are going out of the while-loop.
What you can do is, store you data into another variable, like
$soap_data = "";
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH)){
$soap_data .= " " . implode(" ",$data);
}
//...
$result = $client->submitBatchJob(array('data'=>$soap_data, 'process'=>$NameChecker))
->submitBatchJobResult;
Also, what devpro said, it is always better to include a default for variables.
You need to define $result in default at top level like:
<?php
if (isset($_GET['data']) && $_GET['data'])
{
$result = array(); // ADD THIS
$SelectDataFromRunTable="Select Reference, Variant, HGVSVar FROM run29012016";
$QueryResult=mysqli_query($conn,$SelectDataFromRunTable);
while($data = mysqli_fetch_array($QueryResult,MYSQLI_BOTH))
{
print_r($data);
$data=implode(" ",$data);
}//end of while
$NameChecker='astringtest';
$options = array('features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new SoapClient($URL, $options);
try
{
$result = $client->submitBatchJob(array('data'=>$data, 'process'=>$NameChecker))
->submitBatchJobResult;
}
catch (Exception $e)
{
echo $e->getMessage();
}
print_r($result);
mysqli_close($conn);
}
?>
What i have changed?
I am adding $result = array(); in default.
You are trying to access $result outside where this var was defined.
try this:
try {
$result = $client->submitBatchJob(array('data'=>$data, 'process'=>$NameChecker))
->submitBatchJobResult;
print_r($result);
} catch (Exception $e) {
echo $e->getMessage();
}

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 to sqlite3 - can't upload

I have been trying to make a project where I need to upload information to a sqlite3 database. For that I'm using simple PHP scripts.
I succeeded already uploading information from a PHP script to a database with something like this:
<?php
try
{
$db = new PDO('sqlite:mydatabase.db');
$db->exec("INSERT INTO temps (zone,temperature) VALUES ('maia',77)");
echo "Row Inserted\n";
}
catch(PDOException $e)
{
print $e->getMessage();
}
?>
Now I am struggling to do the same with a script lie this:
<?php
$data = htmlspecialchars($_GET["temp1"]);
$file = "temps.txt";
$current = file_get_contents($file);
$current .= $data;
file_put_contents($file, $current);
try
{
$db = new PDO('sqlite:teste1.db');
$db->exec('BEING;');
$db->exec('INSERT INTO temps (temperature) VALUES ($temp1)');
$db->exec('COMMIT;');
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
My table "temps" has a schema like this:
CREATE TABLE temps (temperature NUMERIC);
Is it because of the var type in the PHP since I declared it as numeric in the database? If so how can I solve that?
Appreciate all your ideas.
Thank you
You might be interested in prepapred statements and (named|positional) parameters:
<?php
$temp1 = '1234';
try
{
$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec('CREATE TABLE temps (temperature NUMERIC)');
$stmt = $db->prepare('INSERT INTO temps (temperature) VALUES (?)');
$stmt->execute( array($temp1) );
}
catch (PDOException $e) {
echo $e->getMessage();
}

Getting MSSQL Stored Proc Results with PHP PDO

I have a reasonably complicated stored procedure in MSSQL 2008 R2 that, in the end, results in a small table being returned. The PHP will be called from javascript and I want it to return the array as JSON to be used in table in the javascript.
I am using PHP to access it and, using the profiler, can see that I am calling the SP and passing the correct parameters to it.
My PHP looks like this:
try {
$dbh = new PDO("sqlsrv:Server=(local);Database=cddDispo");
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo json_encode("Error connecting to the server.");
die ();
}
$lot = $_POST["lot-input"];
$layerAdder = $_POST["layer-input"];
$adder = substr($layerAdder,-3,3);
$adder = str_replace('=','',$adder);
$layer = substr($layerAdder,0,strpos($layerAdder,' '));
$sth = $dbh->prepare('EXEC dbo.pullDispo ?,?,?');
$sth->bindParam(1,$lot,PDO::PARAM_STR);
$sth->bindParam(2,$layer,PDO::PARAM_STR);
$sth->bindParam(3,$adder,PDO::PARAM_STR);
$array = array();
try {
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
//I want to build my output array here
}
}catch (PDOException $e) {
echo "Error getting data, please try again.";
die();
}
header('Content-type: application/json');
echo json_encode($array);
This is the first time that I have tried to return table results from a stored procedure and even with several PHP Manual/ Google searches I have not figured out how to capture the table back in the PHP. I have a less elegant workaround (write the SP table to a static table and call that table later in the PHP) but would rather figure out if I can do in a more elegant manner. Any advice is much appreciated.
I thought it might be useful if I posted my final code:
function array_push_assoc($array,$key,$value) {
$array[$key] = $value;
return $array;
}
header('Content-type: application/json');
try {
$dbh = new PDO('sqlsrv:Server=(local);Database=cddDispo');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo json_encode('Error connecting to the server.');
die ();
}
$lot = $_POST['lot'];
$layer = $_POST['layer'];
$adder = $_POST['adder'];
$sth = $dbh->prepare('EXEC dbo.pullDispo ?,?,?');
$sth->bindParam(1,$lot,PDO::PARAM_STR);
$sth->bindParam(2,$layer,PDO::PARAM_STR);
$sth->bindParam(3,$adder,PDO::PARAM_STR);
$results = array();
$combinedArray = array();
$array = array();
$count = 0;
try {
$sth->execute();
do {
$results[] = $sth->fetchAll(PDO::FETCH_ASSOC);
}while ($sth->nextRowset());
foreach($results as $row) {
if($count == 0) {
$headerArray =
[
'Lot' =>$row['Lot'],
'Layer' =>$row['Measured Layer'],
'Product' =>$row['MES Product'],
'Adder' =>$row['Adder Chart']
];
$combinedArray = array_push_assoc($combinedArray,'header',$headerArray);
}
$count++;
//This is for formatting of final table
if($row['UDL'] == 0) {
$udl = 'NA';
} else {
$udl = round($row['UDL'],4);
}
$infoArray =
[
'Wafer' =>$row['Wafer'],
'Type' =>$row['Type'],
'Count' =>$row['Count'],
'CDD' =>round($row['CDD'],3),
'UCL' =>round($row['UCL'],4)
];
array_push($array,$infoArray);
}
$combinedArray = array_push_assoc($combinedArray,'detail',$array);
}catch (PDOException $e) {
echo json_encode('Error running stored procedure.');
die();
}
echo json_encode($combinedArray);
Could it be that your stored procedure is returning multiple result sets? This includes output like warning messages or number of rows affected. Try adding SET ANSI_WARNINGS OFF or SET NOCOUNT ON at the top of your stored procedures after the AS. You can also try advancing to the next result set in PHP before trying to get the results by calling $stg->nextRowset() before $sth->fetchAll().
Use fetchAll() to get your resultset, then encode that array as your json response:
$array = array();
try {
if($sth->execute()){
$array = $sth->fetchAll(PDO::FETCH_ASSOC);
}else{
$array = array('error'=>'failed to execute()')
}
}catch (PDOException $e) {
echo "Error getting data, please try again.";
die();
}
header('Content-type: application/json');
echo json_encode($array);
When you are calling a stored procedure with multiple result sets, you probably do not want to add SET NOCOUNT ON into every procedure you have; you always can add
$dbh->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$dbh->query("SET NOCOUNT ON");
before of
$dbh->prepare($query);
and it will work.

PHP Query Where and Like

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());
}

Categories