Doing a query in wordpress? - php

I am editing an index.php file in the themes folder and I just need to run a query but I cant seem to run a query...here is what i tried
i tried to include the config files
<?php require( dirname(__FILE__) . '/wp-load.php'); ?>
<?php print DB_NAME;exit; ?>
that printed nothing
then i tried to do the mysql_query command
mysql_connect($server, $username, $password)
$users = mysql_query("select * ....");
print_r($users); exit;
nothing in either one....i know there has got to be an easier way to do a query in wordpress...any ideas

Don't use mysql directly (as a mysql connection already exists). Instead use the wpdb 'abstraction' - see the wordpress documentation here: http://codex.wordpress.org/Function_Reference/wpdb_Class

Related

Strange inconsistency, database connection from require_once not working in only one place

I've encapsulated my MySQLi connection logic in a script named connect_mysqli.php. This working just fine all over my project (9 other pages are having no trouble), but one page is returning this error:
Warning: mysqli::query(): Couldn't fetch mysqli in C:\xampp\htdocs\projectName\php_calls\AddItem.php on line 193
Here's the code that's not working in AddItem.php:
$sql = <<<HEREDOC
UPDATE listing_data
SET ebay_id = '$responseObj->ItemID'
WHERE listing_id = '$database_listing_id'
HEREDOC;
require_once(__DIR__ . '/connect_mysqli.php'); //this creates $conn
$conn->query($sql); //this is line 193
And this is the code from connect_mysqli.php:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$db = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8");
Again, this is working without trouble in every other spot in the project. Here's what I've tried so far:
I checked my SQL syntax. I echoed the SQL query I'm attempting and tested it on the command line, the query is working fine.
Double check my SQL again. I copied the code from a working database call into the AddItem.php. It produces the same error. I tested the original page where this code exists, it works correctly in that spot.
I checked to make sure require_once is working correctly. To make sure my relative path was working correctly, and I am in the cwd that I expected I was in:
echo require_once(__DIR__ . '/connect_mysqli.php');
and it produced:
C:\xampp\htdocs\projectName\php_calls/connect_mysqli.php
This was expected. I opened Windows Power Shell and ran:
cat C:\xampp\htdocs\projectName\php_calls/connect_mysqli.php
This displays the code inside connect_mysqli.php! I was beginning to guess my require_once was flawed.
Check to see if there's a naming collision.
var_dump(get_defined_vars());
There is only one $conn.
The connection is not being closed with $conn->close();. If it's closing without my instruction I don't know how or why.
I copied and pasted the code from connect_mysqli.php into AddItem.php and the error goes away. So somehow my require_once must be messing up my connection. AddItem.php and connect_mysqli.php are in the same folder. I tried connecting with this line instead:
require_once('connect_mysqli.php');
I still get an error.
Sorry for the incredibly lengthy question, I wanted to do my research and try everything before creating another question on the topic. For now I can copy the database connection code into AddItem as a workaround, but it's bad practice, and there's clearly some important principle escaping me here that I'd like to understand.
Edit: more information
Nico Haase asked the question that put me on the right track. Line 1 of AddItem.php is a require_once:
require_once(__DIR__ . '\return_item_php_obj_by_id.php');
and inside return_item_php_obj_by_id.php we have the culprit:
require_once(__DIR__ . '/connect_mysqli.php');
//edited out irrelevant code
mysqli_close($conn);
In the original post I said "There's no $conn->close() hiding anywhere." Clearly I was mistaken. I found the hidden close(). When I comment this out, the connection works. Now I've accidentally made my code really hard to read, and I don't want to use a database connection that far away on the stack. Should I leave the connection open so I can use it again with AddItem.php? What's best practice in this case?

PHP mysql_query() No such file or directory found?

I have a MySQL database set up with Hostmysite.com. It connects just fine, and the idea of my php file is to take form values and input it into the SQL database. I am trying to create a feature that doesn't allow duplicate entries by comparing the email to see if it exists in the db...
The php code I think is right, but on die() it returns No such file or directory found??? That doesn't make sense.
<?php
//connection variables is excluded to get to the point of the problem
$con = mysqli_connect($host, $user, $pass, $db);
if (!$con){
die("Connection failed: " .my_sqli_connect_err());
}
$email = $_POST["email"];
$email = mysqli_real_escape_string($con, $email);
//see if email exists in database
$findEmail = "SELECT * FROM rsvpWedding WHERE email='" . $email."';";
$results = mysql_query($findEmail)or die(mysql_error());
?>
The:
$results
Returns a No such file or directory exists? I don't understand the SQL statement is correct and I believe my php code is also correct.
I don't know if this has anything to do with the problem, but this does mix:
mysqli_*();
with
mysql_*();
*****UPDATE ******
I believe I understand why I am getting that error of No such file or directory found. According to the web page : http://php.net/manual/en/function.mysql-query.php When sql_query() is executed it tries to connect to a link that was executed on
sql_connect()
not
sqli_connect()
If it can't find one it will try and attempt a connection with sql_connect() with no arguments, if that fails it will generate an error.. From researching online I see that No such file or directory is normally associated with sql_connect() errors.
So i suppose my question to this post sort of changes to how do I create a resource using the sqli_* syntax. I tried
$results = mysqli_query($con, $findEmail) or die(mysql_error());
but that still doesn't work, it just skips that entire code block... doesn't even produce an error.
This might be caused by mysql.sock file path is not configured properly for php.
So please make sure you installed the mysql db engine, and find where the mysql.sock file is located.
Then you need to configure in php.ini file:
Find these lines, configure like the following:
mysql.default_socket = /path/mysql.sock
mysqli.default_socket = /path/mysql.sock
pdo_mysql.default_socket = /path/mysql.sock
Restart apache server and mysql service
You can't mix mysqli_* with mysql_*. It's safer to do it the mysqli way anyways:
//see if email exists in database
$stmt = $con->prepare('SELECT * FROM rsvpWedding WHERE email=?'); // question mark is a placeholder
$stmt->bind_param('s', $email); // 's' means it's a string
$stmt->execute();
$stmt->bind_result($result); // assign the result to your $result var
$stmt->fetch();
See the docs here:
http://php.net/manual/en/mysqli.prepare.php
your not printing anything thats why!
try using mysqli_num_rows($result)
echo that one
if its greater than zero then it exist
if none then youre all good

unable to access certain php pages on localhost

I have a login page,login_form, menu page, and download page , this has been running successfully on a server earlier but i want all this to run on my local host, hence, I copied it all and put it in /var/www/html folder and was able to run the login page but the rest like menu.php and all dont come up.
IT has also a sql database which i just added into my system using, mysql -u root -p exaample < cs303.sql
and it is able to process normal select statements as well
Anybody here happens to know what is happening?
<?php
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
define ('HOSTNAME', 'localhost');
define ('USERNAME', 'root');
define ('PASSWORD', 'merlin');
define ('DATABASE_NAME', 'wicap');
$db = mysql_connect('localhost', 'root', 'merlin') or die ('Cannot connect to MySQL.'); // connecting to database
//echo"l; km;l";
mysql_select_db('wicap.sql');
$v1=$_REQUEST["username"];
$v2=$_REQUEST["password"];
//echo "sdfdf";
//$v1="ritish";
//$v2="ritish_r";
//echo($user);
//echo($pass);
$q=mysql_query("SELECT * FROM login where pass='".$v2."' and user='".$v1."'");
while($r=mysql_fetch_array($q))
{
echo($r[0].$r[1]+"/n");
echo "mohit";
}
mysql_close();
?>
#MerlinSudar: for more clarity i am demonstrating the code here
<?php //first PHP opening tag
//put these lines
ini_set("error_reporting",1)
ini_set('display_errors',1);
. //you code
. //you code
?>
Hope this helps
Follow the below Step hope it will solve your problem...
1) if you are using a xammp the put all your files in the htdocs folder, and if you are using the wammp the put all you file in www folder.
2)Check the linking of file, give the proper link connection.
Enable error reporting
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
Add this code on top of your index file and check
Since mysql is deprecated, please dont use it anymore rather use the improved version
of mysql http://php.net/manual/de/book.mysqli.php

What would cause include_once to break my code in PHP with MySQL?

The code below was not working:
public function __construct($thread_id)
{
require_once('../private/mysqli_connect.php');
require_once('../php_classes/class_message.php');
$this->thread_id=$thread_id;
$q="SELECT *
FROM message_thread_name
WHERE thread_id=2";
if($r=#mysqli_query($dbc, $q))
{
while($row=mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$this->poster=$row['name'];
$this->subject=$row['thread_subject'];
}
}
$qm="SELECT message_id
FROM message
WHERE thread_id=$this->thread_id";
if($rm=#mysqli_query($dbc, $rm))
{
while($rowm=mysqli_fetch_array($rm, MYSQLI_ASSOC))
{
$message=new message($rowm['message_id']);
array_push($this->messages, $message);
}
}
}
I ran out of ideas for fixing it, so I changed require_once('../private/mysqli_connect.php'); to require('../private/mysqli_connect.php');, and much to my surprise, it worked. Any ideas as to why that may be?
Thanks.
When you use require_once PHP will check if the file has already been included, and if so, not include (require) it again. You can read it here.
So whats the problem here?
From your problem statement, I am assuming you have created another instance of this class before, or you have already included mysqli_connect.php somewhere else. And in your mysqli_connect.php you have created the connection link something like.
$dbc= mysqli_connect( ... );
So when you using require_once as the mysqli_connect.php is not loading again, your $dbc variable remain undefined. and your query does not work. But when you use require instead of require_once the file loaded again, and new connection created again, and your code works.
NB: Though changing to require, solved your problem, you should not use it like this. It will create new connection to your database, each time you create new instance of your class. For your thought: you can try creating something like this

creating a separate file to connect to mysql with php

I want to use a single file for my php application to connect to a database when the user register for the first time or login in
what is the code is it same as below is good:
$username="root";
$password="root";
$database="test";
function Save($name)
{
global $username;
global $password;
global $database;
$link = mysql_connect('localhost', $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO test (name)" .
"VALUES ('" . $name . "')";
mysql_query($query);
mysql_close();
}
Also, how can i do the require for that file? it is located in the root of the application folder should but i back slash first after require '/filename.php' or should i put double dots first?
If the file is in the same directory, you could simply use: include_once "db.php";
If it is in parent directory(ie, one level up), then use: include_once "../db.php";
Another one is to append the global DOCUMENT_ROOT with the filename(like others have given examples below).
And also, avoid mysql_* functions. Use PDO or mysqli instead.
Wish you good luck. :)
Your question essentailly boils down to "how can I include a file that is in the root from anywhere". Well, there's two answers.
The first answer is to just use inlude($_SERVER['DOCUMENT_ROOT']."/connect.php");, but that's a lot to type, especially if you have a lot of includes.
Personally, I like to start my script with chdir($_SERVER['DOCUMENT_ROOT']); Then I don't have to worry about where I am anymore - I will always be in the root folder.
Probably it is not good that you open mysql connection on every save, if there will be many such calls per request.
inlude($_SERVER['DOCUMENT_ROOT'] . '/db.php');
A few comments:
First, if you don't need to use the password and username and database elsewhere, you should just define them in the function.
Second, If I'm not mistaken if you put the "/" in front of the path that will take you all the way down to the root of the filesystem, which I'm guessing this user wouldn't have access to. That being said, I would use ".." to navigate up the hierarchy. So use:
require_once("../path/to/file.php")
Rather that putting the include file in the document root, you should create a directory for common include files, and add it to the include_path setting in php.ini. Then you can just do include 'connect.php';.

Categories