Here's the code:
<?php
function widget_hello_world($vars) {
$username = "database_user";
$password = "database_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("database_name",$dbhandle)
or die("Could not select database!");
$test1 = mysql_query("select COUNT(*) FROM Table WHERE `Status`='new'");
mysql_close($dbhandle);
$content = '<table class="table">
<thead><tr><th style="text-align:left;">Title</th><th style="text-align:left;">Data</th></tr></thead>
<tbody>
<tr><td>Test Data 1</td><td>{$test1}</td></tr>
<tr><td>Test Data 2</td><td>{$test2}</td></tr>
<tr><td>Test Data 3</td><td>{$test3}</td></tr>
</tbody>
</table>';
return array( 'title' => 'Hellow World', 'content' => $content );
}
add_hook("AdminHomeWidgets",1,"widget_hello_world");
?>
This is the error message I'm getting when I go to the page:
Connected to MySQL
Unexpected input field parameter in database query.
Obviously it's connecting to the database, but it says there's an issue with the query.
At first I thought the issue was with this line:
$test1 = mysql_query("select COUNT(*) FROM Emails WHERE `Status`='new'");
However, even when I delete that line, the same error keeps on happening. What am I doing wrong?
It seems this error occurs on mysql_close($dbhandle);
However, I also notice that reserved word "Table" should be back-tick to prevent an invalid query. Perhaps something in your callback routine is global and affecting the connection.
Also, use this:
echo mysql_error();
to see any mysql errors during query.
Try to do a separate checking for the DB being selected, like:
<?php $con = mysql_connect('localhost', 'root', 'mypass');
$selected_db = mysql_select_db('DB Name here');
if (!$selected_db)
{
die ('Database not selected : ' . mysql_error());
}
?>
If it says 'Database is not selected' then check the spelling of your Database inside the mysql_select_db(). You could also comment the mysql_close(); just to see if error will still persist.
On the other note it is better to use mysqli_ because mysql_ is deprecated or better yet use PDO.
Related
We have the following code in the HTML of one of our webpages. We are trying to display all of the Wifi speeds and GPS locations in our database using the MySQL call and while loop shown in the below PHP code. However, it doesn't return anything to the page. We put echo statements in various parts of the PHP (ex. before the while loop, before the database stuff) and it doesn't even print those statements to the webpage.
<body>
<h2>WiFi Speeds in the System</h2>
<p>Speeds Recorded in the System</p>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbc = mysql_connect($hostname, $username, $password)
or die('Connection Error: ' . mysql_error());
mysql_select_db('createinsertdb', $dbc) or die('DB Selection Error' .mysql_error());
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
$results = mysql_query($data, $dbc);
while ($row = mysql_fetch_array($results)) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
?>
</body>
This line is incorrect, being the AND:
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
^^^
Change that to and using a comma as column selectors:
$data = "(SELECT Wifi_speed, GPS_location FROM Instance)";
However, you should remove the brackets from the query:
$data = "SELECT Wifi_speed, GPS_location FROM Instance";
Read up on SELECT: https://dev.mysql.com/doc/refman/5.0/en/select.html
Using:
$results = mysql_query($data, $dbc) or die(mysql_error());
would have signaled the syntax error. Yet you should use it during testing to see if there are in fact errors in your query.
Sidenote:
AND is used for a WHERE clause in a SELECT.
I.e.:
SELECT col FROM table WHERE col_x = 'something' AND col_y = 'something_else'
Or for UPDATE, i.e.:
UPDATE table SET col_x='$var1'
WHERE col_y='$var2'
AND col_z='$var3'
Footnotes:
Consider moving to mysqli with prepared statements, or PDO with prepared statements, as mysql_ functions are deprecated and will be removed from future PHP releases.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
"Thank you for the suggest but we tried that and it didn't change anything. – sichen"
You may find that you may not be able to use those functions after all. If that is the case, then you will need to switch over to either mysqli_ or PDO.
References:
MySQLi: http://php.net/manual/en/book.mysqli.php
PDO: http://php.net/manual/en/ref.pdo-mysql.php
hi mate i see some problem with your DB connection & query
here is example check this out
in SELECT is incorrect, being the AND .using a comma as column selectors:
and make condition for after set query & check data validation that is proper method
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "createinsertdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT `Wifi_speed `, `GPS_location `, FROM `Instance`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
} else {
echo "0 results";
}
$conn->close();
?>
Hi I'm having problems accessing my server i'm using mysql on my laptop apache2 and php. my problem is i can seem to connect to db but can't get any data out of the registered table inside the db. Thanks in advance always i'm running window7.
<?php
$username = "root";
$password = "deslap";
$hostname = "localhost";
#connection to the database seems to work and prints connected to MySQL
$dbhandle = mysql_connect($hostname, $username, $password)or die("Unable to connect to MySQL");
echo "<br />Connected to MySQL<br>";
#select a database to work with
$selected = mysql_select_db('registered',$dbhandle)or die("Could not select database");
#execute the SQL query and return records.
$result = mysql_query("SELECT id, Name FROM registered");
while($row = mysql_fetch_array($result))
{
echo "ID:".$row{'id'}." Name:".$row{'name'}."Email: ".$row{'Email'};
}
?>
</body>
</html>
Change the curly brackets to box brackets (you can use either {} or [], but square brackets are conventional for working with array elements) -
echo "ID:".$row['id']." Name:".$row['Name']."Email: ".$row['Email'];
You're also selecting only 'id' and Name (change 'name' to 'Name') so Email will not be returned.
For some reason, the following code inside the query works in my MySQL command console, yet when I try to run it as a Query in PHP, something keeps going wrong and I'm not sure what. Here is the code I've done so far.
//2. Perform database query
$query = "SELECT skills.element_id, content_model_reference.element_id, element_name FROM skills, content_model_reference WHERE (skills.element_id = content_model_reference.element_id)";
$result = mysql_query($query);
//Tests if there was a query error
if(!$result){
die("Database query failed.");
}
Is there something preventing the code that worked in MySQL (The line with SELECT) from working, or is my syntax somehow wrong?
EDIT: So it's saying I didn't select a database. Yet I thought I had. Here is the code above it:
//1. Create a database connection
$dbhost = "host"; //Host: Can be either an IP address, or a domain (like google.com).
$dbuser = "user";//User: The user that is connecting to the database.
$dbpass = "pass";//Password: This is the password that the user is using.
$dbname = "db";//Name: This is the name of the database.
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);//The value, 'handle,' is the connection.
//Test if connection occurred. Die ends the program/php, and in this case, also prints a message
if(mysqli_connect_errno()){
die("Database connection failed: ".
mysqli_connect_error().
" (". mysqli_connect_errno() . ")"
);
}
Like I said, the error message I am getting is pertaining only to the query, the server is fine with my database connection.
You're using mysqli_* for the connection, but you're using mysql_* for the QUERY... don't think you can do that, has to be one or the other (MYSQLI_ preffered). Also the query should be:
$result = mysqli_query($connection,$query);
My php code is below:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db="newsportaldb";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($db,$dbhandle)
or die("Could not select DB");
$sql= mysql_query('select username from tbl_login');
while($rss= mysql_fetch_array($sql))
{
$ress["homepagecontents"][] = array("titles"=>$rss['username']);
}
echo json_encode($ress);
mysql_close($dbhandle);
?>
//in this case we getting "?????????????????" as a result of echo json_encode($ress);
The Question marks come from wrong charset.
Make sure that the connection has right charset (utf8).
If on phpmyadmin you dont see the data correctly so change the db,table and column to utf8_general_ci.
Hot recommend for you: upgrade your code and use php PDO Object.
Good luck !
Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)