I'm trying to retrieve multiple data from a database with a PHP function, but somehow when I do this multiple times it gives a MySQL connection error.
$heat=getStat("heat", $userid);
$cash=getStat("cash", $userid);
echo mysql_error();
I use the code above to assign variables by calling a function which retrieves the stats from a database.
When I use the above codes separately, they work. But when I put them together they fail.
Is this a simple you-are-a-beginner-noob-programming-mistake?
I forgot to post the function so here it is:
function getStat($statName,$userID) {
require_once 'config.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die('Error connecting to MySQL' . mysql_error());
mysql_select_db($dbname);
$query = sprintf("SELECT value FROM user_stats WHERE stat_id = (SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
mysql_real_escape_string($statName),
mysql_real_escape_string($statName),
mysql_real_escape_string($userID));
$result = mysql_query($query);
list($value) = mysql_fetch_row($result);
return $value;
}
The problem is most likely caused by the require_once. As this is where you are pulling in your config for the database connection. The second time the require is executed it will not pull in the code required to define your database connection vars.
As #MichaelBerkowski has stated, it would be much better to have one global connection when the script loads, and make use of this connection for each request to the database. However if you wish to stick with the way you have currently, this should solve the problem:
function getStat($statName,$userID) {
require 'config.php'; /// <-- note this has changed to just require
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("SELECT value FROM user_stats WHERE stat_id = (SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
mysql_real_escape_string($statName),
mysql_real_escape_string($statName),
mysql_real_escape_string($userID));
$result = mysql_query($query);
list($value) = mysql_fetch_row($result);
return $value;
}
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'm having a connection errors trying to connect with PHP to mySQL. I'm using a video instructable, because I've been having several of these connections before, but it is outdated and I'm trying to use mysqli instead of mysql commands, but I'm winding up with nothing posting on my pages, I think because of this.
Can you tell me if this would be the correct translation of it?
function user_exists($username) {
$username = sanitize($username);
$query = mysqli_query("SELECT COUNT('user_id') FROM 'users' WHERE 'username' = '$username'");
Sanitize is defined on another page (and included) as:
<?php
function sanitize ($data) {
return mysqli_real_escape_string($data);
}
?>
Please help!
First you need connect to MySQL..is your function have that ? It is incomplete..on the screen..
example..
$link = mysqli_connect("localhost","root","","database") or die("Error " . mysqli_error($link));
$query = "SELECT `release_year` FROM film LIMIT 5" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
I am new in PHP .. I need help to make a PHP code to update data in MySQL if data exists and if don't already exists then insert data in MySQL.. I have made the PHP code to do this but it's inserting data when data already exists.. in MySQL.. Please help
$con = mysql_connect('localhost','root','root');
$db = mysql_select_db('gamingtracker',$con);
$query = "SELECT * FROM servers WHERE sgame='$game_insert'";
$result = mysql_query($query, $con);
While($row = mysql_fetch_array($result)) {
$id = #$row['id'];
$sname = #$row['sname'];
$sgame = #$row['sgame'];
$minplayers = #$row['minplayers'];
$maxplayers = #$row['maxplayers'];
$ip = #$row['ip'];
$port = #$row['port'];
$map = #$row['map'];
}
$sname1= html_entity_decode("{$server['s']['name']}");
if(#$sname=="{$server['s']['name']}"
AND #$sgame=="{$server['s']['game']}"
AND #$minplayers=="{$server['s']['players']}"
AND #$maxplayers=="{$server['s']['playersmax']}"
AND #$ip=="{$server['b']['ip']}"
AND #$port=="{$server['b']['c_port']}"
AND #$map=="{$server['s']['map']}" )
{
$query1 = "UPDATE servers
SET sname='$sname1', sgame='{$server['s']['game']}', minplayers='{$server['s']['players']}', maxplayers='{$server['s']['playersmax']}', ip='{$server['b']['ip']}', port='{$server['b']['port']}', map='{$server['s']['map']}'
WHERE ip='{$server['b']['ip']}', port='{$server['b']['port']}', sgame='{$server['s']['game']}'";
$result1 = mysql_query($query1, $con);
}
else {
$query1 = "INSERT INTO servers (id,sname,sgame,maxplayers,minplayers,ip,port,map) VALUES ('','$sname1','{$server['s']['game']}','{$server['s']['players']}','{$server['s']['playersmax']}','{$server['b']['ip']}','{$server['b']['c_port']}','{$server['s']['map']}')";
$result1 = mysql_query($query1, $con);
}
So you only want one entry per unique combination of ip, port, and sgame? The most straightforward way would be to let mysql handle this.
First, create a unique index on the table for those fields. Run the following in mysql:
CREATE UNIQUE INDEX ip_port_sgame ON servers (ip, port, sgame);
Then, instead of running an INSERT query, use REPLACE. So just change this one line in your php:
UPDATE servers
to
REPLACE INTO servers
I have two databases, one online (mysql) and one in my office (SQL Server) which I would like to compare and update where a value is different.
I am using php to connect to the SQL Server database and run a query to retrieve the information, then connecting to the Mysql database running a query. Then I need to compare the two queries and update where necessary.
Is there somewhere I can look for tips on how to do this, I am sketchy on PHP and struggling really.
This is as far as I have got-:
<?php
$Server = "**server**";
$User = "**user**";
$Pass = "**password**";
$DB = "**DB**";
//connection to the database
$dbhandle = mssql_connect($Server, $User, $Pass)
or die("Couldn't connect to SQL Server on $Server");
//select a database to work with
$selected = mssql_select_db($DB, $dbhandle)
or die("Couldn't open database $DB");
//declare the SQL statement that will query the database
$query = "SELECT p.id, p.code, ps.onhand";
$query .= "FROM products p with(nolock)";
$query .= "INNER JOIN productstockonhanditems ps with(nolock)";
$query .= "ON ps.ProductID = p.ID";
$query .= "WHERE ps.StockLocationID = 1";
//execute the SQL query and return records
$get_offlineproduct2 = mssql_query($query);
mysql_connect("**Host**", "**username**", "**password**") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$get_onlineproducts = mysql_query(SELECT w.ob_sku, w.quantity
FROM product_option_value AS w
ORDER BY ob_sku)
or die(mysql_error());
//close the connection
mssql_close($dbhandle);
?>
I am looking to compare the value p.code to w.ob_sku and whenever they match copy the value of ps.onhand to w.quantity so the online database has the correct quantities from the office database.
My question I guess is how close am I to getting this right? Also am I doing this the right way, I don't want to get so far and realise that i am just wasting my time...
Thanks!
You do not need to fetch any record from MySQL, since you actually want to update it.
I would do something like this:
$query = 'SELECT p.code, ps.onhand FROM (...)';
// execute the SQL query and return a result set
// mssql_query() actually returns a resource
// that you must iterate with (e.g.) mssql_fetch_array()
$mssqlResult = mssql_query($query);
// connect to the MySQL database
mysql_connect("**Host**", "**username**", "**password**") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
while ( $mssqlRow = mssql_fetch_array($mssqlResult) ) {
$mssqlCode = $mssqlRow['code'];
$mssqlOnHand = $mssqlRow['onhand'];
mysql_query(
"UPDATE product_option_value SET quantity = $mssqlOnHand WHERE ob_sku = $mssqlCode"
// extra quotes may be required around $mssqlCode depending on the column type
);
}
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()";
}