Calling a php file from a simple HTML form - e.g., - get php source code in browser as result (see below).
Figured issue is that PHP is not running on localhost (using older version of MAMP). Checked, double-checked, and upgraded to latest MAMP PRO version (2.1.4).
Still have the same problem - PHP & Apache configs look correct.
Thoughts? (guessing that first suggestion will be to ditch MAMP.)
PHP:
<?php
//Open a database connection
$con = mysqli_connect('localhost', 'root', 'root') or die( mysql_error() ); mysql_select_db($database) or die( mysql_error() );
//Declare variables for form data
$toDoItem = mysql_real_escape_string ($_POST["toDoItem"]);
$toDoDue = mysql_real_escape_string ($_POST["toDoDue"]);
$toDoOwner = mysql_real_escape_string ($_POST["toDoOwner"]);
//Query
$sql = "INSERT INTO toDo
(toDoItem, toDoDue, toDoOwner)
VALUES ($toDoItem, $toDoDue, $toDoOwner)";
$result = mysql_query($sql) or die( mysql_error() );
if($result){
echo ("<br>Data input successful.");
} else {
echo ("<br>Data input failed.");
}
//close the connection
mysql_close();
?>
Do you get the MAMP screen when you go to localhost? I think that if you get the screen but click on PhpInfo it will also print out regular php statements.
It seems that it's because of a faulty install
Related
I already know that if you want to connect to a database using MySQL you have to provide the correct URL, username, password that is the normal thing here is my code:
<?php
$mysql_id = mysql_connect('localhost', 'root', '');
mysql_select_db('Booklet', $mysql_id);
if(!$mysql_id)
{
echo"cannot connect to database ";
}
?>
This code runs well, however if I messed with the username which is root it still connects here is the code:
<?php
$mysql_id = mysql_connect('localhost', 'rot', '');
mysql_select_db('Booklet', $mysql_id);
if(!$mysql_id)
{
echo"cannot connect to database ";
}
?>
Can anyone explain to me why is this happening?
As of PHP 5.5.0 mysql_* functions are deprecated and you should not code with thoses. Think of thoses function as a crawling zombie, you don't go and kiss it, do you ?
You should use MySQLi or PDO for doing operations on database. Please don't bother with mysql_* anymore, you dont want that. It's like asking to code on Windows Milenium, hell, even booting this thing is a nightmare.
Anyway, to answer the question you should write :
$mysql_id = mysql_connect('localhost', 'rot', '') or die(mysql_error());
Or better, you should look at the doc of MySqli and be free of thoses shackles. Think about that, please.
You never bothered checking for failure. Your code simply assumes success and blunders onwards.
$mysql_id = mysql_connect('localhost', 'rot', '') or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
mysql_select_db('Booklet', $mysql_id) or die(mysql_error());
All of the mysql_*() function return boolean false on failure. You need to check for that false. Never ever assume a DB operation succeeded. Always assume failure, check for that failure, and treat success as a pleasant surprise.
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
try to debug your code by adding mysql_error() like this
$mysql_id = mysql_connect('localhost', 'rot', '');
mysql_select_db('Booklet', $mysql_id);
echo " debug return: " . mysql_error();
or simply update your code if you have a newest version of php > 5.5.0
$mysql_id = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
Using the new MySQLi functions, you would get a false back on trying to connect, also you can pass you database as fourth parameter. So your code could look like this:
<?php
if($mysql_id = mysqli_connect('localhost', 'root', '', 'Booklet'))
{
/* do something like mysqli_query($mysql_id, ... */
}
else
{
echo"cannot connect to database ";
}
?>
Im using phpgraph lib to create graphs on my linux server. I tried an example and it worked, but I had provided it with the data.
then I wanted to connect it to mysql database and plot a query, when I run it, nothing happens, I don't see any output on the page or any errors, I don't see any output on the page at all, even if I put wrong credentials to my database e.t.c any inputs?
I have executed the sql statement on sql server and it's working fine.
the version of php the server has is PHP 5.3.3
<?php
include('phpgraphlib.php');
$graph= new PHPGraphLib(550,350);
$link = mysql_connect('localhost', 'user', 'password')
or die('Could not connect: ' . mysql_error());
mysql_select_db('databasename' or die('Could not select database');
$dataArray=array();
//get data from database
$sql="my sql statement";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$salesgroup=$row["var1"];
$count=$row["count"];
//add to data areray
$dataArray[$salesgroup]=$count;
}
}
//configure graph
$graph->addData($dataArray);
$graph->setTitle("Sales by Group");
$graph->setGradient("lime", "green");
$graph->setBarOutlineColor("black");
$graph->createGraph();
?>
I fixed it, I was expecting to see errors on the webpage, but didn't see any on CHROME, I hen opened it in IE and saw error 500.
Troubleshooted through the log file.
Turned out the sql statement wasn't suppose to have double quotes e.g instead of
where name="john"
it's suppose to be
where name='john'
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 have a MSSQL database. I wrote a php page to connect and retreive data from it. The code works on my localhost.
$strCon = "Provider=SQLOLEDB;Data Source=local;database=test;uid=sa;pwd=go;";
$strAlias = "GEORGE";
$strSql = "SELECT LINK FROM LINKS WHERE ALIAS = '" . $strAlias . "'";
$Con = new COM ("ADODB.Connection") or die("Cannot start ADO");
$Rs = new COM ("ADODB.Recordset") or die("Cannot start ADO");
$Con->open($strCon);
$Rs->open($strSql,$Con,1,3);
if (!$Rs->EOF && !$Rs->BOF) {
$strTargetLink = $Rs->Fields['LINK'];
echo $strTargetLink;
}
$Rs->Close();
$Con->Close();
$Rs = null;
$Con = null;
When I run this code on the server, I receive some error? when echo $strTargetLink; row is executed, word
Object
is received on the sent html page and also in the source code of that page.
I am running PHP on IIS as a FastCGI application. Both PHP 4.4.7 and 5.2.6 are supported.
Any ideas? What does this Object text mean?
Thanks.
Instead of using echo, I now tried
var_dump($strTargetLink);
and received the information
object(COM)(1) { [0]=> resource(3) of type (COM) }
try using var_dump instead of echo. it will at least give you more information about the object contained in $strTargetLink.
I have found a solution and now it works. So just in case you would like to connect with ADO, I am writing what I have done.
Instead of
$strTargetLink = $Rs->Fields['LINK'];
I wrote
$strTargetLink = $Rs->Fields(0);
Why do I get a "mysql_query(): supplied argument is not a valid" for the first...
$r = mysql_query($q, $connection);
In the following code...
$bId = trim($_POST['bId']);
$title = trim($_POST['title']);
$story = trim($_POST['story']);
$q = "SELECT * ";
$q .= "FROM " . DB_NAME . ".`blog` ";
$q .= "WHERE `blog`.`id` = {$bId}";
$r = mysql_query($q, $connection);
//confirm_query($r);
if (mysql_num_rows($r) == 1) {
$q = "UPDATE " . DB_NAME . ".`blog` SET
`title` = '{$title}',
`story` = '{$story}'
WHERE `id` = {$bId}";
$r = mysql_query($q, $connection);
if (mysql_affected_rows() == 1) {
//Successful
$data['success'] = true;
$date['errors'] = false;
$date['message'] = "You are the Greatest!";
} else {
//Fail
$data['success'] = false;
$data['error'] = true;
$date['message'] = "You can't do it fool!";
}
}
I also get an "mysql_num_rows(): supplied argument is not a valid MySQL result resource" error too.
Side notes: I am using 1&1 Hosting (worst hosting ever), custom .htaccess file with one line text to enable PHP 5.2 (only way with 1&1 Hosting).
Extra stuff add after the questions was posted...
Here is how $connection is defined. It is on its own page called connection.php that is called up using the require_once function. It it is called up on every page that require a database connection including the one in question...
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database Connection Failed: </br>" . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database Selection Failed: </br>" . mysql_error());
}
... I know it is working because this the same connect that I use for the page I have and I have no problems with it. I havent testing on my home server yet, but I am going to later to see if it is related to a 1&1 Hosting issue.
UPDATE: I am in the process of moving from 1&1 Hosting to HostMoster. 1&1 runs a PHP as CGI and runs PHP4 instead of PHP5 (you can make a custom .htaccess file to make it run PHP5). I will update you later.
The first would be because it's not a connection, and the second would be because it's not a query result because it wasn't a connection. Use mysql_error() to figure out what went wrong in the connection.
My guess is that $connection has not been properly opened. You should have a line like:
$connection = mysql_error($server, $user, $pass);
Also check mysql_error() to see the reason why it's failing.
I think that cletus meant to suggest that you need to have a mysql_connect() instead of mysql_error() before you attempt to perform a mysql_query(). It will probably look like this (with the exception that 1and1 may have given you a specific hostname to connect to for your database which you should use in place of localhost below):
//Make sure this goes before any of your other mysql_* functions
$connection = mysql_connect('localhost', 'yourUserName', 'yourPassword');
Passing $connection around for each of your queries isn't really necessary unless you have multiple database connections open concurrently that you are using and need to make sure to differentiate between the two when making query calls. Otherwise, mysql_query assumes that you are using the last database that you connected to.
Also, for security purposes as mentioned by Frank you should use mysql_real_escape_string() like so:
$q = "SELECT * ";
$q .= "FROM " . DB_NAME . ".`blog` ";
$q .= "WHERE `blog`.`id` = ".mysql_real_escape_string($bId).";
Tested on my local system (via WAMP), I had no problems. At the time when I had problems, I was using 1&1 Hosting. 1&1 Hosting run PHP as CGI, which probably cause my problems. I couldnt handle allof the crap with 1&1 and switch to HostMonster. Now, I don't any issues. Plus, I rather use cPanel over 1&1's admin panel.