Add MySQL result into PHP array - php

I would like to add results into array and print on screen.
Here's my code and nothing is printing...could someone help me take a look.
include('config.php');
$con = mysql_connect($host, $username, $password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db('members', $con) or die(mysql_error()) ;
$sql = "SELECT * FROM people where status like '%married%' ";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$result_array[] = $row['id']; // <-------**here**
}
return $result_array;
echo($result_array);
mysql_close($con);

You're doing a return before you do the echo/mysql_close, so the echo/close calls never get executed. Unless you've got more code around this snippet, there's no point in having that return call, as you're not actually in a function, so the return is effectively acting as an "exit()" call, since you're already at the top of the execution stack.

Firstly, change:
mysql_select_db(mtar, $con) or die(mysql_error());
To:
mysql_select_db('mtar', $con) or die(mysql_error());
Then remove return $result_array; - you don't need it and when used outside of a function it just halts execution of the script.
Finally, change
echo($result_array);
to:
print_r($result_array);
EDIT: Some additional thoughts:
You don't need parentheses around the argument to echo - it's actually more efficient to leave them out: echo $var; is quicker than echo($var);
If you're only ever going to use the id column, then don't select the whole row: use SELECT id FROM instead of SELECT * FROM.
Are you sure you need the wildcards either side of "married"? You may well do (depends on what the possible values of status are), but you probably don't. So
$sql = "SELECT id FROM people where status = 'married' ";
May be better,

Related

PHP: json_encode() doesn't show anything with multidimensional array

I'm trying to make a simple PHP script that fetches a table from my MySQL database and encodes the results in JSON, so I can use them later in Java.
This is my code:
<?php
$servername = "localhost:3036";
$username = "example_user";
$password = "example_password";
$conn = mysql_connect($servername, $username, $password);
if(! $conn) {
die("Could not connect: " . mysql_error());
}
$sql = "SELECT * FROM table_name";
mysql_select_db("database_name");
$retval = mysql_query($sql, $conn);
if(! $retval) {
die("Could not get data: " . mysql_error());
}
while($row = mysql_fetch_assoc($retval)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($conn);
?>
This just gives a blank page as output (error messages are set to display).
However, if I change json_encode($output) to json_encode($output[0]) (or any other number within the array's bounds), the output becomes that one $row array.
This is probably a really stupid question, but after about 3 hours of research I'm at my wit's end. Thank you for any help.
User #Joni led me to the solution.
Adding mysql_set_charset("utf8") fixed my issue.
As mentioned in this post: Why is this PHP call to json_encode silently failing - inability to handle single quotes?.
Try
echo json_encode($output) ;
It seems you have some utf8 character in your result set
add this statement before running your query
mysql_query('SET CHARACTER SET utf8');
Update
"mysql"
to
"mysqli"
and add
mysqli_set_charset($variável_de _conexão, 'utf8');
below the connection variable

Display MySQL Database as an array

I have a MySQL database full of user information, like their username, password, email, etc.
I want a PHP script that allows me to pull JUST their username and display it like so:
"username1","username2","username3"
Literally exactly like that, the quotes and all.
EDIT: Sorry for not supplying enough information.
The table is named "users" the field I want to pull off it is "username" I can get it to pull and display all the information, my only problem is imploding it.
OK dude, read the comments
<?php // open a php tag
$dbc = mysql_connect("host", "username", "password"); // connect to database
mysql_select_db("db_name", $dbc) // select the database
$sql = "SELECT `username` FROM `users_table`"; // select only the username field from the table "users_table"
$result = mysql_query($sql); // process the query
$username_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$username_array[] = "\"".$row['username']."\""; // get the username field and add to the array above with surrounding quotes
}
$username_string = implode(",", $username_array); // implode the array to "stick together" all the usernames with a comma inbetween each
echo $username_string; // output the string to the display
?>
I've seen all the other answers, however have you considered using PDO instead of mysql_query functions? It's a much nicer way to work with the database.
Here's what you want to achieve in a few lines of code (using lamba functions):
$dbh = new PDO("mysql:host=localhost;dbname=test", "yourusername", "yourpassword");
$results = $dbh->prepare("SELECT u.username FROM users u");
$results->execute();
$results = $results->fetchAll();
echo implode(", ", array_map(function(&$r) { return $r['username']; }, $results));
Output: Jamie, Bob, Chris
Nice and clean. Also, you should check if you have any results that have been returned and if the query was successful.
Just another approach.
EDIT: I've just realised you're a beginner so my answer may be a bit too advanced. However, i'll leave it for others to see as a solution, and perhaps you might look into using PDO an lamba functions when you learn a bit more. Best of luck.
Let's assume that you have a 'mydb' database and 'users' table in it.
SQL needed:
USE mydb;
SELECT username from users;
Short version:
Wrap it in PHP calls to mysql PHP library
Get result as an array then implode it with comma symbol.
Long version:
First we need to connect to database:
$db = mysql_connect('DATABASE_HOST', 'USER', 'PASSWORD');
if (!$db) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('mydb', $db);
if (!$db_selected) {
die ('Can\'t use mydb: ' . mysql_error());
}
Remember to always check the return values of functions.
Then we query the database:
$result = mysql_query('select username from users', $db);
...and fetch results in flat array (we need only usernames):
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC))
{
$data[] = $row['login'];
}
Then we format the returned data according to your specs:
$string_result = '"'. implode('", "', $data) . '"';
You can do with $string_result anything you want, just close the database connection immediately after use:
mysql_close($db);
Good luck with learning PHP, BTW. ;)
You could using PHP's implode, but it's probably easier just do it in SQL assuming that the list won't be too long:
SELECT GROUP_CONCAT(CONCAT('"', username, '"')) AS usernames
FROM your_table

Php Custom Function For Mysql Query Not Working

I have created two functions one for connecting to MySQL database and one for running a specific query.
I enter the database name as parameter for first function to connect to the database, this works fine, but my problem is with the second one.
2nd function returns the $result from running a query, but when I use mysql_fetch_array with the $result, it gives one output even if it supposed to give more than one.
As I am no php expert so i can't find the solution. Please help me.
Here is the code:
File Function.php
<?php
function myconnect($data)
{
$db_host='localhost';
$db_user='root';
$db_pwd='';
$data=$data;
$dbc = mysqli_connect($db_host, $db_user,$db_pwd,$data) or die (mysql_error());
return $dbc;
}
function runquery($db,$table,$tcol,$tid)//(databse,table,column_name,identifier)
{
$dbc=myconnect($db);
$query="SELECT *FROM ".$table." WHERE ".$tcol."=".$tid." ORDER BY first_name ASC";
$result = mysqli_query($dbc, $query);
return $result;
}
?>
File test.php
<?php
require_once('testfunc.php');
$result= runquery('user','user_basic','user_type','1');
//runquery('database','table','col','id')/
while($row=mysqli_fetch_array($result))
{
echo '<strong>First Name:</strong>' . $row['first_name'] . '<br/>';
}
?>
If I am doing all wrong then suggest me a better way :-)
A quick glance shows that in your function runquery
SELECT *FROM
should be
SELECT * FROM
note the space after the *
EDIT :
I also notice you are using *mysqli_fetch_array* and this is not a valid mysqli method. You are right in using the mysqli extension over mysql but you should look more into statement fetch to solve this issue. The link I provided give a procedural example that should work for what you need.
function myconnect($db)
{
/*Removed redundant - single use variables*/
/*DB name was passed to the client_flags parameter of mysql_connect instead of mysql_select_db*/
$dbc = mysql_connect("localhost", "root","") or die (mysql_error());
/*Inserted Line*/
mysql_select_db($data);
return $dbc;
}
Currently you're not selecting a database - equivalent of USE DATABASE db_name.
Couple of syntax changes and function definition
function runquery($db,$table,$tcol,$tid)//(databse,table,column_name,identifier)
{
$dbc=myconnect($db);
/*Query and link identifier were in the wrong order*/
return mysql_query("SELECT * FROM ".$table." WHERE ".$tcol."=".$tid." ORDER BY first_name ASC", $doc);
}
Finally a couple of syntax changes, function calls
require_once('testfunc.php');
$result= runquery('user','user_basic','user_type','1');
/*fetch associateive array of result during iteration*/
while($row=mysql_fetch_assoc($result))
{
echo '<strong>First Name:</strong>' . $row['first_name'] . '<br/>';
}

Why is my php script freezing?

What is causing my php code to freeze? I know it's cause of the while loop, but I have $max_threads--; at the end so it shouldn't do that.
<html>
<head>
<?php
$db = mysql_connect("host","name","pass") or die("Can't connect to host");
mysql_select_db("dbname",$db) or die("Can't connect to DB");
$sql_result = mysql_query("SELECT MAX(Thread) FROM test_posts", $db);
$rs = mysql_fetch_row($sql_result);
$max_threads = $rs[0];
$board = $_GET['board'];
?>
</head>
<body>
<?php
While($max_threads >= 0)
{
$sql_result = mysql_query("SELECT MIN(ID) FROM test_posts WHERE Thread=".$max_threads."", $db);
$rs = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT post FROM test_posts WHERE ID=".$rs[0]."", $db);
$post = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT name FROM test_posts WHERE ID=".$rs[0]."", $db);
$name = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT trip FROM test_posts WHERE ID=".$rs[0]."", $db);
$trip = mysql_fetch_row($sql_result);
if(!empty($post))
echo'<div class="postbox"><h4>'.$name[0].'['.$trip[0].']</h4><hr />' . $post[0] . '<br /><hr />[Reply]</div>';
$max_threads--;
}
?>
</body>
</html>
First, I'd suggest completely getting rid of the extraneous HTML bits. Then, build up your code slowly, line-by-line to see if you can find the offending line. So write a script that just connects to the database and see what happens.
If you find for example that this code...
<?php
$db = mysql_connect("host","name","pass") or die("Can't connect to host");
mysql_select_db("dbname",$db) or die("Can't connect to DB");
?>
...is causing the freeze on its own, then it could easily be a problem with the MySQL server.
However, if the browser itself is crashing, that sounds like an issue with your system rather than something that PHP or MySQL is doing...
Try this 1 SQL query instead of those 1 + (4 * n) queries:
SELECT MIN(ID), post, name, trip FROM test_posts GROUP BY Thread
Maybe a LIMIT 50 (or whatever max # of threads to return) at the end as well, that could be a lot of data.
You can just loop over the results of this query instead of $max_threads and all the extra db calls, via while ($row = mysql_fetch_row($sql_result)) { /* echo(...); */ }.
Not sure that's exactly the same as what you're trying to fetch without knowing more about the data (getting the root post of each thread in a forum?), but it should be pretty close.
(P.S.: if that's a threaded 2ch-style forum deal, I'm not sure that's an ideal db design. A parent-child adjacency list might be better than maintaining a number count for each thread. Just a guess though.)
I'm thinking it's because you're hitting the sql database 4 times per loop. Is there any way you can maybe access it all at once, and then parse the incoming data from there?
$dbsql = 'SELECT * FROM my_database';
$result = mysql_query($dbsql);
while($row = mysql_fetch_array($result)) {
// Parse information here, rather than
// accessing the database for individual variables...
}
Something like that.
Update:
Other than what I've already said (and you've dismissed) all I see are some here & there coding quirks:
This part didn't have a space between echo and the string. The 'hr' element didn't have a starting bracket.
echo '<div class="postbox"><h4>'.$name[0].'['.$trip[0].']</h4><hr>' . $post[0] . '<br /><hr />[Reply]</div>';
'while' Shouldn't be capitalized.
while($max_threads >= 0)
Again, clean code is a good place to start, but that's all I've got, personally. I just recently cleaned up my own site, which was crashing IE (and no other browser), simply because it had too many markup errors. Hope it helps.
Maybe you can scatter calls to this simple function in yer code:
function of($required)
{
$args = func_get_args();
var_dump($args);
ob_flush();
flush();
}
of(__LINE__, $max_threads);
You can also use something like this for your queries:
function mydb_query($query, $db = null)
{
$args = func_get_args();
$result = call_user_func_array('mysql_query', $args);
if (!$result) {
of(array(__FUNCTION__), mysql_error(), $sql);
//return something else?
}
return $result;
}
$result = mydb_query("SELECT post, name, trip FROM test_posts WHERE ID = (SELECT MIN(ID) FROM test_posts WHERE Thread={$max_threads})", $db);
You should use mysqli/PDO/framework with support for prepared statements.
Probably the script is exceeding the maximum server execution time threshold, try this on the top of your file to confirm this:
ini_set('max_execution_time', '180');

PHP will not delete from MySQL

For some reason, JavaScript/PHP wont delete my data from MySQL! Here is the rundown of the problem.
I have an array that displays all my MySQL entries in a nice format, with a button to delete the entry for each one individually. It looks like this:
<?php
include("login.php");
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("<br/><h1>Unable to connect to MySQL, please contact support at support#michalkopanski.com</h1>");
//select a database to work with
$selected = mysql_select_db($dbname, $dbhandle)
or die("Could not select database.");
//execute the SQL query and return records
if (!$result = mysql_query("SELECT `id`, `url` FROM `videos`"))
echo 'mysql error: '.mysql_error();
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
?>
<div class="video"><a class="<?php echo $row{'id'}; ?>" href="http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?>">http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?></a><a class="del" href="javascript:confirmation(<? echo $row['id']; ?>)">delete</a></div>
<?php }
//close the connection
mysql_close($dbhandle);
?>
The delete button has an href of javascript:confirmation(<? echo $row['id']; ?>) , so once you click on delete, it runs this:
<script type="text/javascript">
<!--
function confirmation(ID) {
var answer = confirm("Are you sure you want to delete this video?")
if (answer){
alert("Entry Deleted")
window.location = "delete.php?id="+ID;
}
else{
alert("No action taken")
}
}
//-->
</script>
The JavaScript should theoretically pass the 'ID' onto the page delete.php. That page looks like this (and I think this is where the problem is):
<?php
include ("login.php");
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
echo ("Video has been deleted.");
?>
If there's anyone out there that may know the answer to this, I would greatly appreciate it. I am also opened to suggestions (for those who aren't sure).
Thanks!
In your delete.php script, you are using this line :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
The $id variable doesn't exists : you must initialize it from the $_GET variable, like this :
$id = $_GET['id'];
(This is because your page is called using an HTTP GET request -- ie, parameters are passed in the URL)
Also, your query feels quite strange : what about this instead :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = '$id' ");
ie, removing the '.' : you are inside a string already, so there is nothing to concatenate (the dot operator in PHP is for concatenation of strings)
Note :
if this works on some server, it is probably because of register_globals
For more informations, see Using Register Globals
But note that this "feature" has been deprecated, and should definitely not be used !
It causes security risks
And should disappear in PHP 6 -- that'll be a nice change, even if it breaks a couple of old applications
your code has a big SQL injection hole : you should sanitize/filter/escape the $id before using it in a query !
If you video.id is a string, this means using mysql_real_escape_string
If you where using the mysqli or PDO extensions, you could also take a look at prepared statements
with an integer, you might call intval to make sure you actually get an integer.
So, in the end, I would say you should use something that looks like this :
$id = $_GET['id'];
$escaped_id = mysql_real_escape_string($id);
$query = "DELETE FROM `videos` WHERE `videos`.`id` = '$escaped_id'";
// Here, if needed, you can output the $query, for debugging purposes
mysql_query($query);
You're trying to delimit your query string very strangely... this is what you want:
mysql_query('DELETE FROM `videos` WHERE `videos`.`id` ='.$id);
But make sure you sanitize/validate $id before you query!
Edit: And as Pascal said, you need to assign $id = $_GET['id'];. I overlooked that.
In your delete.php you never set $id.
You need to check the value in $_REQUEST['id'] (or other global variable) and ONLY if it's an integer, set $id to that.
EDIT: Oh, also you need to remove the periods before and after $id in the query. You should print out your query so you can see what you're sending to the sql server. Also, you can get the SQL server's error message.
You add extra dots in the string.
Use
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='$id'");
instead of
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
Also check how do you get the value of $id.
Thanks everyone. I used Pascal MARTIN's answer, and it comes to show that I was missing the request ($_GET) to get the 'id' from the precious page, and that some of my query was incorrect.
Here is the working copy:
<?php
include ("login.php");
$id = $_GET['id'];
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = $id ");
echo ("Video ".$id." has been deleted.");
?>
Thanks again!

Categories