Got a strange error saying that I'm not connected to a database while running a mysqli_num_rows query. Here is the code:
<?php include("php/functions.php"); ?>
<?php
if(isset($_GET['verification']) && !empty($_GET['verification'])){
// Verify data
$hash = mysqli_real_escape_string($con, $_GET['verification']); // Set hash variable
$search_sql = "SELECT 'hash', active FROM members WHERE hash='".$verification."' AND active='0'";
$search_res = mysqli_query($con, $search_sql);
$match = mysqli_num_rows($search_res);
Any ideas why this isn't working?
I have changed several things in your code, please review.
If you are using the mysqli class then anything after your class instatiation should look something like:
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
$con->exampleClassFunction()
using the object operator ->.
To get the num_rows your object operator would be after the query variable, like so:
$search_res = $con->mysqli_query($con, $search_sql);
$match = $search_res->mysqli_num_rows($search_res);
I also added the backticks to all applicable column names in your query:
SELECT `hash`, `active` FROM members WHERE `hash`='".$verification."' AND `active`='0'
Here is an example with your code:
//include("php/functions.php");
$DB_NAME = 'DATABASE_NAME';
$DB_HOST = 'DATABASE_HOST';
$DB_USER = 'DATABASE_USER';
$DB_PASS = 'DATABASE_PASSWORD';
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
// Added a connection error check before continuing
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_GET['verification']) && !empty($_GET['verification'])){
$hash = $con->mysqli_real_escape_string($con, $_GET['verification']);
// Use back ticks on query column names,
// use single quotes for comparative operations
$search_sql = "SELECT `hash`, `active` FROM members WHERE `hash` = '".$verification."' AND `active` = '0'";
$search_res = $con->mysqli_query($con, $search_sql);
$match = $search_res->mysqli_num_rows($search_res);
}
<?php include('functions.php'); ?>
Also, make sure you have your closing ?> tag in the correct place.
just try to make it include("functions.php")..
I think thats your problem
<?php
include("functions.php"); //includes databse connection
$search_sql = "SELECT hash, active FROM members WHERE hash='".$verification."' AND active='0'";
$search_res = mysqli_query($con, $search_sql);
$match = mysqli_num_rows($search_res);
?>
include("functions"); or include("functions.php"); ??? You forgot .php
You forget to add file extension.
<?php include("functions.php"); ?>
also put `
around hash as its reserved word by MySQL.
please try the below code:
<?php
include("functions.php"); //includes databse connection php file
$search_sql = "SELECT hash, active FROM members WHERE hash='".$verification."' AND active='0'";
$search_res = mysqli_query($con, $search_sql);
$match = mysqli_num_rows($search_res);
?>
include should have a .php file as parameter. please check it.
Related
I am trying to update for some products their category in database. I want to find products that have in their name a specific word and after that I want to update the category for this products.
I want to select IDs from sho_posts where sho_posts.post_title contain this part of word '%Audio CD%' and after that to update the sho_term_relationships.term_taxonomy_id with value 2 where sho_term_relationships.object_id=sho_posts.id.
I wrote a little PHP code but it make only selection part. What is wrong?
<?php
$username = "user_name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("1812233_shoping",$dbhandle)
or die("Could not select examples");
echo "Connected to MySQL<br>";
$result = mysql_query ("SELECT `id` FROM `sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%' ");
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}."<br>";
}
$sql = "UPDATE 'sho_term_relationships'
SET 'term_taxonomy_id' = '123'
WHERE 'object_id' = $row";
//close the connection
mysql_close($dbhandle);
My new cod for script now is:
$username = "_shoping";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("_shoping",$dbhandle)
or die("Could not select examples");
echo "Connected to MySQL<br>";
$result = mysql_query ("SELECT `id` FROM `sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%' ");
while ($row = mysql_fetch_array($result)) {
$id[] = $row['id'];
/*echo "ID2:".$id."<br>";*/
}
foreach ($id as $value) {
echo "value:".$value."<br>";
}
/*$id = $row['id'];*/
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = '123'
WHERE object_id =".$value;
mysql_query($sql);
//close the connection
mysql_close($dbhandle);
now it make an update but only for one row, how to make for all rows? From select query I get 4 result
Try this:
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = '123'
WHERE object_id = ".$row{'id'};
And make sure to run the query mysql_query($sql)
Also, I think you might want to add this query inside the while loop
You are using single quotes instead of backticks (which are in this case not necessary). Change your update query to this:
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = 123
WHERE object_id = $row";
Also, you are missing some pieces of your code; nothing will be called on that query. It's not being executed at all.
Also you have some other problems here, mainly due to the high risk of sql injection. First of all stop using mysql_ functions, they are deprecated. You should prepare your variables. Here's a demonstration of the key parts of your script in mysqli_ format.
This should also solve most of your issues (there may be a few more if I don't full understand your original question).
You would call your database like this (and check for errors)
$dbhandle = new mysqli($hostname, $username, $password);
if ($dhandle->connect_error) {
die("Connection failed: " . $dbhandle->connect_error);
}
Then you would select your data like this (assuming that term might not be the same every time, and might be coming from a post variable named search).
Edit: For example, if you have an HTML form that is getting this variable like so:
<input type="select" name="search_term" />
you name the variable like this:
$search = $_POST['search_term'];
and then you set it up for your query for the like operator
$search_term = '%'.$search.'%';
$result = $dbhandle->prepare("SELECT `id`
FROM `sho_posts`
WHERE CONVERT(`post_title` USING utf8)
LIKE ? ");
$result->bind_param("s",$search_term);
$result->execute();
$result->bind_result($id);
And then you can get your data through the while loop like so
while ($result->fetch()) {
... stuff you want to do here...
}
$result->close();
Then you would use this in your update query (which would take a similar syntax), and you can just get the information from $id which was created with the bind_result above:
$sql = $dbhandle->("UPDATE sho_term_relationships
SET term_taxonomy_id = 123
WHERE object_id = ?");
$sql->bind_param("s",$id);
$sql->execute();
$sql->close();
It may take a little bit to get used to this, but I find it easier to parse, and also is much more secure
i really dont know why this code isnt working.. database connection works, the timestamp is written to the database.
But i cant figure out why i get a blank page with this code here (i should see the timestamp as echo).
Anyone an idea about this ?
Thank you!
<?php
$user = "daycounter";
$password = "1234";
$database = "daycounter";
$host = "localhost";
$date = time();
// Create connection
$conn = new mysqli($host, $user, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Error: " . $conn->connect_error);
}
//Insert timestamp in database
$sql = "INSERT INTO datum (datum)
VALUES ('".$date."')";
//check if that worked
if ($conn->query($sql) === TRUE) {
echo "That worked!";
}
//get timestamp from db and display it as echo
$select = "SELECT 'datum' FROM 'daycounter'";
$result = mysql_query($select);
while($row = mysql_fetch_object($result))
{
echo "$row->datum";
}
?>
You're using a mysqli DB connection, but calling mysql to do your select. You cannot mix/match the database libraries like that. If you'd had even minimal error checking, you'd have been told that there's no connection to the db:
$result = mysql_query($select) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^
Plus, your select query has syntax errors. 'daycounter' is a string literal - you cannot select FROM a string. 'datum' would be syntactically correct, you can select a string literal from a table, but most like you want:
SELECT datum FROM daycounter
or
SELECT `datum` FROM `daycounter`
Neither of those words are a reserved word, so there's NO need to quote them, but if you're one of those people who insist on quoting ALL identifiers, then they must be quoted with backticks, not single-quotes.
$select = "SELECT 'datum' FROM 'daycounter'";
$result = mysqli_query($conn, $select);
while($row = mysqli_fetch_object($result)) {
echo "$row->datum";
}
This question already has answers here:
php/mysql with multiple queries
(3 answers)
Closed 3 years ago.
I've a doubt with mysqli_query..
this is a part of my code:
$con = db_connect();
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
$result = mysqli_query($con, $sql);
return $result;
I can't do the query...
If I try to do a query like this:
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
It works.
What's the problem?? I can't use SET with mysqli_query?
Thanks
You can not execute multiple queries at once using mysqli_query but you might want to use mysqli_multi_query as you can find out in the official documentation:
http://www.php.net/manual/en/mysqli.multi-query.php
Lets start with creating a working php script.
<?php
// replace for you own.
$host ="";
$user = "";
$password = "";
$database = "";
$con= mysqli_connect($host, $user, $password, $database);
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
// Begin SQL query
$sql = "SELECT * FROM users";
$result = mysqli_query($con,$sql) OR Die('SQL Query not possible!');
var_dump($result);
return $result;
var_dump($result);
// End SQL query
mysqli_close($con);
};
?>
INSERT query:
$sql= "INSERT INTO categorias(name) VALUES ('ssss')";
mysqli_query ($con,$sql) OR Die('SQL Query not possible!');
UPDATE and DELETE query:
$sql= "DELETE FROM users WHERE username = 'Hola';";
$sql.= "UPDATE users SET foreign_key_checks = 0 WHERE username = 'Hola'"; /* I made a guess here*/
mysqli_multi_query ($con,$sql) OR Die('SQL Query not possible!');
Check the SET query. I think something is missing. I have changed it to what I think was your aim.
The connection should be established like this:
$Hostname = "Your host name mostly it is ("localhost")";
$User = "Your Database user name default is (root)"//check this in configuration files
$Password = "Your database password default is ("")"//if you change it put the same other again check in config file
$DBName = "this your dataabse name"//that you use while making database
$con = new mysqli($Hostname, $User , $PasswordP , $DBName);
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
In this query:
put categorias in magic quotes(`) and column names also
For your next query do this:
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
Change to:
$sql= "SET foreign_key_checks = 0; DELETE FROM `users` WHERE `username` = 'Hola'";
im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.
Here is my error:
Warning: mysql_query() expects parameter 2 to be resource, null given...
This refers to line 23 of my code which is:
$result = mysql_query($sql, $connection)
My entire query code looks like this:
$query = "SELECT * from users WHERE userid='".intval( $_SESSION['SESS_USERID'] )."'";
$result = mysql_query($query, $connection)
or die ("Couldn't perform query $query <br />".mysql_error());
$row = mysql_fetch_array($result);
I don't have a clue what has happpened here. All I wanted to do was to have the value of the users 'fullname' displayed in the header section of my web page. So I am outputting this code immediately after to try and achieve this:
echo 'Hello '; echo $row['fullname'];
Before this change, I had it working perfectly, where the session variable of fullname was echoed $_SESSION['SESS_NAME']. However, because my user can update their information (including their name), I wanted the name displayed in the header to be updated accordingly, and not displaying the session value.
Your $connection variable is NULL that's what your error message is referring to.
Reason being is that you have not called mysql_connect. Once called it will assign you a resource where you can set it to the $connection variable, thus being non-null.
As an example:
$connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');
// now $connection has a resource that you can pass to mysql_query
$query = "SELECT * from users WHERE userid='".
intval( $_SESSION['SESS_USERID'] )."'";
$result = mysql_query($query, $connection)
include the mysql connections on your class file, for example:
connections/mysql.php
<?
$hostname_MySQL = "localhost";
$database_MySQL = "database";
$username_MySQL = "user";
$password_MySQL = "password";
$MySQL = mysql_pconnect($hostname_MySQL, $username_MySQL, $password_MySQL) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_MySQL,$MySQL);
?>
class.php
<?
include "Connections/MySQL.php";
class utils {
public function myFunction()
{
global $MySQL;
$sql = "select * from table";
$rs = mysql_query($sql, $MySQL) or die(mysql_error());
$filas = mysql_fetch_assoc($rs);
$totalFilas = mysql_num_rows($rs);
...
}
}
?>
You have two ways of doing this, you need to use mysql_connect to connect to your database, you can pass this to mysql_query if you desire, if you don't pass anything to mysql_query PHP uses the last link opened from mysql_connect
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
Have you connected to your database? If so please show this code too.
For now, just try removing the $connection variable, like this:
$result = mysql_query($query);
And see where that gets you.
$connection is assigned the value of the database connection resource id. You don't have that in your script, so the value of $connection is NULL, and that is why you are getting the error. You need to connect to the database before using mysql_query(). You should be okay after that.
You need to do:
$connection=mysql_connect('host','user','pass');
if($connection === false) {
echo "Error in connection mysql_error()";
}