Convert PDO sqlite query to array - php

I'm having a bit of a problem with sqlite on my website and I cannot figure out what I'm doing wrong. I am trying to retrieve content from a row in an sqlite database, which works, but it is stored as a "object" variable. I am trying to convert it to a php "array()". I have tried several ways of doing this but all have failed. This is very frustrating and was wondering if anyone could be kind enough to help. The reason I need this done is so that I can compare 2 arrays to see if there are any matching texts in either of them.
Here is my current code:
include("template.php");
// Create (connect to) SQLite database in file
$file_db = new PDO('sqlite:Scrambled/data.sqlite');
// Set errormode to exceptions
$file_db->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$result = $file_db->query('SELECT * FROM users');
//$results = array(mysql_fetch_assoc($result));
$resultslist = array();
while(($row = mysql_fetch_assoc($result))) {
$resultslist[$row] = $row['users'];
}
$qualifiedpeople = explode("\n", file_get_contents('Scrambled/roboticsmembers.txt'));
//$lol = array(fetch_assoc($qualifiedpeople));
$members = array_intersect($qualifiedpeople, $resultslist);
echo("$resultslist");
echo("$qualifiedpeople");
//foreach($members as $member) {
//echo("$member \n");
//}
As you can see I have tried different things and some lines are commented out for later reference.
You can see the error right here: citadelwars.net/members.php
"Warning: mysql_fetch_assoc() expects parameter 1 to be resource, object given in C:\wamp\www\members.php on line 12"
I have not found this error in all of my googling, but I'm sure it means that the pdo is giving me an "object" variable when it needs to be a resource. Can you tell me if there's any way around fixing this?

I've found the solution and what I did wrong;
I was able to replace:
while(($row = mysql_fetch_assoc($result))) {
$resultslist[$row] = $row['users'];
}
With this:
$i = 0;
foreach($result as $row) {
$resultslist[$i] = $row['name'];
$i++;
}
Which worked perfectly.
Also for comparing the tables I replaced explode("\n", with explode("\r\n",

Related

Mysql results as PHP named variables

I have a table in mysql called site_settings that looks like this
Table in PHPMyAdmin
I am trying to store all of my website settings in mysql and want to pull them into PHP as variables.
I want to pull all values from the variable_name column as the $variable names in PHP and have their values set to whats in the variable_type column.
$site_name = Vexed
$registration_enabled = False
here is my code:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$$row['variable_name'] = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
the last two lines i am using to see if the variable have been created but i cant get it to work. the best result i have got so far is
[Array] => Array
(
[variable_name] => Vexed
)
Can anyone tell me where i am going wrong?
Thanks in advance to anyone who can help.
What you're trying to duplicate is PHP's extract() builtin function.
It's generally considered a bad practice, because it will make your code harder for readers to understand or debug.
What is so wrong with extract()?
How to demonstrate an exploit of extract($_POST)?
https://dzone.com/articles/php-bad-practice-use-extract
https://blog.josephscott.org/2009/02/05/i-dont-like-phps-extract-function/
What I think is happening is that when you call $$arr['variable_name'] it's actually doing $$arr first (which evaluates to $Array after the string conversion), and then trying to assign into assign the ['variable_name'] key into $Array.
I would expect this minor modification to work:
$sql = connect($database_address, $database_username, $database_password, $database);
$query = "SELECT * FROM site_settings";
$result = $sql->query($query);
//$row = $result->fetch_all(MYSQLI_ASSOC);
while($row = $result->fetch_assoc())
{
$name = $row['variable_name'];
$$name = $row["variable_type"];
}
$arr = get_defined_vars();
print_r($arr);
Edit: I'll also echo, that it's a little bit weird to dynamically create variables in this way and it will make your code hard to follow.

Get column information from results of mysql query in php?

I am trying to print out the column headers for any query entered. I have other code that connects to the database and actually prints the results, but I am having trouble with the line
'$result .= $heading->name;'
I keep getting this error:
'Catchable fatal error: Object of class mysqli_result could not be converted to string in...'
Could someone explain what the problem is? According to the php manual this should give me the right information. I am fairly new to php though, so if you improve the code could you please explain how you did it?
I have the following code so far that gets a result from a query:
$result = mysqli_query($conn,$query);
if($result){
if( mysqli_num_rows($result)>0){
$columnNo = mysqli_num_fields($result);
for($i=0;$i<$columnNo;$i++){
$heading = mysqli_fetch_field_direct($result,$i);
$result .= $heading->name;
}
}
}
$result is an object being used by mysqli. Then you try to append a string onto the end of it.
Just use a different variable name besides $result which will be a string in which you will collect the names of your columns. Or you might save the names in an array like this:
$var[] = $heading->name;
since $result is an object you are using for executing the query, i won't be able to store any other data coming from db. you have to take another variable (say $variable) to store the data coming from db. Follow the below code:
$result = mysqli_query($conn,$query);
$variable=''; // add this
if($result){
if( mysqli_num_rows($result)>0){
$columnNo = mysqli_num_fields($result);
for($i=0;$i<$columnNo;$i++){
$heading = mysqli_fetch_field_direct($result,$i);
$variable .= $heading->name; //modify here
}
}
}
I hope this will solve the issue..

PHP probletm with appending new property into object?

I am starting to learn php for interaction with mysql db.
I have to fetch data from two unrelated tables and form an array of stdClass objects then dump it as json array.
I have so far managed to fetch data from table1 and added some columns from it into an
myobjects[], as follows..
Here $array is an array of primary keys , also i pass a reference to myobjects array
function load_from_table1($array , &$myobjects)
{
foreach($array as $num)
{
$obj=(object)null;
$obj->prop1 = $num;
$sql="SELECT * FROM `table1` WHERE col1=".$num;
$result = mysqli_query($con, $sql);
if($result!=null)
{
$row = mysqli_fetch_assoc($result);
//inserting data into object
$obj->prop2 = $row['col2'];
$obj->prop3 = $row['col3'];
$obj->prop4 = $row['col4'];
}
$myobjects[]=$obj;
}
}
It is fine so far now i need add two more properties to all items in myobjects array obtained from table2.
function load_from_table2(&$data)
{
for($i=0;$i<sizeof($data);$i++)
{
$obj=(object)$data[$i];
$id=$obj->prop1;
$sql="SELECT * FROM `table2` WHERE col1=".$id;
$result = mysqli_query($con, $sql);
if($result!=null)
{
$row = mysqli_fetch_assoc($result);
//$temp=$row['name'];
//echo $temp;
//$obj->name = "test1";
$obj->name = $row['name'];
//$temp=$row['description'];
//echo $temp;
//$obj->description = "test2";
$obj->description = $row['description'];
}
}
When i dump myobjects as json there is no output. But $temp echos properly , also when i us direct values every thing seems to work fine.
Can some one help me with this, also an explanation on what i am doing wrong would be greatly appreciated. Thank You.
Some Details on the working Environment , Because of the answer i provided ,
I am using wampserver 2.5 64 bit , and for now executing the php file off firefox browser.
The situation is quiet confusing as i can read the value and print it or save to variable , but not save it as object property.
I got it to work, But the problem was not with the code. It seems that the column in the table that i was reading has collation set to ' utf8_general_ci ' not sure what that means. But when i removed that setting , it all worked as expected. But i feel the collation is not the actual underlying reason. So i will keep this question open in hopes some might provide an explanation.
It seems i was looking for the wrong issues. Reading up on collation i found that some character sets are not supported fully , so i tried to echo the contents of the object array instead of json_encode and found it printed.
searching to that end i found another qst here on stackoverflow that solved my problem.
Simply added this line :: mysqli_set_charset($con,'utf8'); before i started any queries on that table and json_encode started working.

How to run a mysql loop from a posted array and extract results to a CSV file

I have searched for hours to try and find a simple answer to this query I am having. I'm very sure it is covered in many ways, by other answers at least partially. I need a clear answer specific to what I am doing because I'm having difficulty trying to put together an answer that works for me from a bunch of other differently formatted and structured questions/answers.
I have a form which is posting a range of results intended to be used as keys for a mysql lookup loop. This is working fine - my post results in a successful array. For example:
$payarr = $_POST['pay'];
print_r($payarr);
Results in:
Array ( [0] => 12 [1] => 7 [2] => 1 )
Which is good given that the I want to run a mysqli process select the rows where claim_id is each of the values in $payarr. I then want to use fputcsv to write each of these rows fully, into a CSV file that is uniquely named by the days date and time that this is all run.
I have fragments of code that don't work and my frustration at trying to cobble something together that does work is getting a bit nuts. Can someone please show me how to do this effectively?
At the moment my code looks like this (but fails miserably):
<?php
include ("../conf/dbconfig.php");
include ("../conf/funcs.php");
include ("../conf/privs.php");
if($privs == 500) {
$view = $_POST['view'];
$payarr = $_POST['pay'];
$ts = date('Ymd-His');
print_r($payarr); //Testing to make sure our array to select from has arrived here ok.
//ob_start();
$fp = fopen('../csv/ResultsFile_'.$ts.'.csv', 'w');
foreach($payarr as $val) {
$result = mysqli_query($con, "'SELECT * FROM claims' WHERE claim_id='$val'");
//$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
while ($row = mysqli_fetch_array($result)) {
echo $payarr;
echo $val;
//fputcsv($fp, $row);
print_r($row);
}
}
fclose($fp);
// return ob_get_clean();
} else {
header("Location: http://www.google.com.au/");
die;
}
?>
I'm willing (and happy) to rewrite the entire thing just as long as it works, so any help and suggestions are very appreciated!
Thanks in advance.
BTW - The $view value is not important in this process but is here as it will be passed back to the resulting header once this all works.
A few rough suggestions (you may need to adapt):
1) Change your query to use IN for the possible values, so you only have to execute one DB query:
$result = mysqli_query($con, "SELECT * FROM claims WHERE claim_id IN (" . implode(",",$payarr) . ")");
2) Make sure you are actually getting a DB result, instead of just assuming:
if(!$result || mysqli_num_rows($result) == 0) {
die("We didn't get any results from the DB!"); // Obviously you'll want better error handling
}
3) Now you can open your file, knowing that you need it. Make sure to verify it worked, since you could easily hit a permissions issue:
$fp = fopen('../csv/ResultsFile_'.$ts.'.csv', 'w');
if(!$fp) {
die("We couldn't open the CSV file for writing, check permissions!"); // Obviously you'll want better error handling
}
4) Now loop through your DB results and store them:
while ($row = mysqli_fetch_array($result)) {
fputcsv($fp, $row);
}
5) Does your CSV file need a header row? If so change mysqli_fetch_array() to mysqli_fetch_assoc() and stick this inside your loop:
while ($row = mysqli_fetch_assoc($result)) {
if(!isset($header)) {
$header = array_keys($row);
fputcsv($fp, $header);
}
fputcsv($fp, $row);
}
6) Only now should you close your file (in your code you do it inside the foreach loop):
fclose($fp);
7) Sanitize your $payarr. It could be as simple as:
$payarr = is_array($_POST['pay']) ? array_map('intval', $_POST['pay']) : array();
You may want to do more than that. But at least you're guaranteed to have an array with only integer values (and as long as you have no claim_id values of 0, it's harmless to have zeros in the array).
Hope that helps, at least track down where your code is failing.

How to display all data from a table?

Well i've been searching google, but I still can't find out how to do this.
I'm a beginner in php so i'm really stumped.
Anyways what I need to do is get all the data from a table and display it on my page.
Like
Contents of row 1
Contents of row 2
etc.
Well that's nice, get down voted for asking for help.
This might help you
print_r() displays information about a variable in a way that's readable by humans.
print_r(), var_dump() and var_export() will also show protected and private properties of objects with PHP 5. Static class members will not be shown.
Remember that print_r() will move the array pointer to the end. Use reset() to bring it back to beginning.
http://php.net/manual/en/function.print-r.php
This is pretty much PHP DB access 101
$pdo = new PDO('mysql:host=localhost;dbname=myDbName', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT * FROM a_table');
$stmt->execute();
$resultSet = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($resultSet as $idx => $row) {
echo '<p>Contents of row ', $idx + 1, '</p><dl>';
foreach ($row as $col => $val) {
printf('<dt>%s</dt><dd>%s</dd>',
htmlspecialchars($col),
htmlspecialchars($val));
}
echo '</dl>';
}
I think google should have given you your answer since this is a rather easy to answer question, but when starting, you don't always know what to search for.
Anyways, hope this helps.
<?php
// connect with you database, returns boolean so you know if you succeeded or not
$con = mysql_connect($database,$username,$password);
if(!$scon){
die('Could not connect to database'); // Stop execution if connection fails
}
//create your query
$query = "Place your database query here";
//get the results
$result = mysql_query($query);
//now you want to go through each row of the result table and echo the contents, or
//use them for whatever reason
while($row = mysql_fetch_array($result)){
echo $row['field_you_want_to_display'];
echo $row['another_field_you_want_to_display']; //You see where this is going
}
//After doing what you want, close the connection to the database
mysql_close($con);
?>
Also, you may want to take a look at the documentation of php for find out what functions you have not seen before do.

Categories