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/>';
}
Related
I need some help with my PHP. I have a trouble with fetching the data from the database. I have hired a PHP developer who did not do his job properly that he have messed up the code which make it don't work so I need some help to fix the issue to get it working again.
When I try this:
//open the database File
$db = new SQLite3('myChannel.db');
if(!$db)
{
echo $db->lastErrorMsg();
}
else
{
$channel_name = $_GET['channels'];
$sql ="SELECT channel, title, start_date, stop_date, description FROM programs WHERE channel='$channel_name'";
$results = $db->query($sql);
while ($row = $results->fetchArray())
{
print_r($row);
}
What happen with the code is it will not fetching the matched data from the database as it will not do anything. I think there is something wrong with the $sql variable.
What I'm expecting to do is I want to look for data in the database where I use the variable called $channel_name, then I want to fetch the matched data to output them in my PHP.
Can you please help me how I can fetch the matched data in the database?
Try this code based on the SQLite PHP docs
class MyDB extends SQLite3 {
function __construct() {
$this->open('myChannel.db');
}
}
$db = new MyDB();
if (!$db) {
echo $db->lastErrorMsg();
} else {
$channel_name = $_GET['channels'];
$sql = "SELECT channel, title, start_date, stop_date, description FROM programs WHERE channel='{$channel_name}'";
$results = $db->query($sql);
while($row = $results->fetchArray(SQLITE3_ASSOC) ) {
print_r($row);
}
}
I changed a few things. I turned your database connection into a class, and I changed your while to include SQLITE3_ASSOC.
Warning: OP's code and as a result this answer has code that is
vulnerable to SQL Injection!
I want make "daily tip" to my website but i don't know how. I think i can use PHP and mysql database but how i can make it? Or can i make example .txt file and some php function choose dailytip from .txt file? I alredy tried this code:
Iam making website which shows daily tip to user. How I can select random value from database.
Here is what I tried:
<?php
function random_tip()
{
$link = mysql_connect ("host", "user","pass", "a2955851_SW")
or die("Error " . mysql_error($link));
mysql_select_db("a2955851_SW");
$sql = "SELECT * FROM `randomtip` ORDER BY RAND() LIMIT 1()";
$row = mysql_query($sql, $link)
or die("Error: ".mysql_error($link));
mysql_free_result($row);
mysql_close($link);
return ($row['tip']);
}
?>
$row = mysql_query($sql, $link)
^^^--- statement handle
return ($row['tip']);
^^^^^^^--- using statement handle as if it was a row of results
You should have
$result = msyql_query(...);
$row = mysql_fetch_assoc($result);
echo $row['tip'];
instead
Note that the mysql_*() functions are obsolete/deprecated, and should not be used in any new code.
Newbie question about PostgreSQL. I'm migrating a MySQL/PHP app I've created, hosted on a Linux server, to PostgreSQL/PHP on a MacOSX Lion Server environment. It's my first experience with Postgres. The first query I'm testing doesn't work as it returns nothing (not even an error message, whichever check code I add). What did I do wrong? I've read articles on the web including the doc on php official website but all comments, personal methods and differences from version to version, either with Postgres or PHP, make it very confusing and I eventually don't understand exactly show I should write my query and fetch_array. Thanks for any suggestions.
Here is my code from the original MySQL application:
// below is the "connexion.php" file
function connexion ()
{
$link=#mysql_connect ("localhost","username","pwd");
if ($link && mysql_select_db ("database"))
return ($link);
return (FALSE);
}
// below is the "index.php" file
require ("connexion.php");
connexion() or exit();
$reqcount = mysql_query ("SELECT * FROM people");
$result = mysql_num_rows($reqcount);
echo "Total : ".$result." people";
mysql_free_result ($reqcount);
mysql_query("set names 'utf8'");
$reqcat = mysql_query ("SELECT catname FROM categories ORDER BY catname");
while ($fieldcat = mysql_fetch_array($reqcat))
{
$name = $fieldcat[catname];
echo $name."<br>";
}
mysql_free_result ($reqcat);
mysql_close ();
And here is the PostgreSQL adaptation:
// connexion.php
function connexion ()
{
$link=pg_connect("host=localhost port=5432 dbname=database user=username password=pwd connect_timeout=5 options='--client_encoding=UTF8'");
return ($link);
}
// index.php
require ("connexion.php");
$reqcount = pg_query ($link,"SELECT * FROM people");
$result = pg_num_rows($reqcount);
echo "Total : ".$result." people";
pg_free_result ($reqcount);
$reqcat = pg_query ($link,"SELECT catname FROM categories ORDER BY catname");
while ($fieldcat = pg_fetch_array($reqcat))
{
$name = $fieldcat[catname];
echo $name."<br>";
}
pg_free_result ($reqcat);
pg_close ();
The php code for postgresql doesn't call connexion() so it never connects, unlike the mysql code.
You can try your query if it fails display error
$reqcount = pg_query ($link,"SELECT catname FROM people") or die(pg_last_error());
This way you can see your error.
errors
UPDATE:
Remove the # in your connection to see the error, and add or die(pg_last_error())
to see the error
I am attempting to search a SQL table from a PHP script. the SQL table is a word list and in the PHP I call a Python script to do the permutations of a given word. Everything is working until I actually go to execute the mysql_query. I need some formatting advice on how to pass so many values to a Select statement. From what I've seen it needs to be in the form ('a','b','c',...) and this is how it is formatted but I'm not getting a return on the actual execution.
<?php
ini_set('display_errors','On');
error_reporting(E_ALL);
$con= mysql_connect("127.0.0.1","app","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("wordlookup");
//Retrieve the data.
$word = $_POST['data'];
$perm = exec("python comb.py $word");
$query="SELECT * FROM words WHERE IN (" .$perm. ")";
print $query;
$sql=mysql_query($query);
print $sql;
mysql_close($con);
?>
This is all of the PHP file, the output from the python call would be in the 'a','b','c'... format and the random prints are just debugging. The print $sql doesn't actually put out anything at the moment.
Thanks,
Kyle
SELECT * FROM words WHERE IN (...)
Your query is missing a condition. WHERE what IN ...? You need to fill in a column name there.
Further, if a query is not working, ask the database why it didn't work:
$result = mysql_query($query);
if (!$result) {
echo mysql_error();
}
Though solution is strange (use external script executed via exec to calculate permutations?), I'd answer your exact question.
$perm_arr = explode(' ', $perm);
function quote($str) { return "'$str'"; }
$perm_arr = array_map('quote', $perm_arr);
$sql = "select * from words where word in (" . join(', ', $perm_arr) . ")";
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,