I am getting errors (not really errors, just not working properly) and I'm trying to figure out if it's related to my sql connections. I have 2 separate connections to two entirely different databases.
$dshost = "kjbkb";
$dsdatabase = "kjhk";
$dsusername = "hjgfytdf";
$dspassword = "jhv";
mysql_connect($dshost,$dsusername,$dspassword);
mysql_select_db($dsdatabase) or die( "Unable to select database");
$sql = "SELECT * FROM users WHERE `username` = '".$_POST['paydl']."'";
$cheeseburger = mysql_query($sql);
$res = mysql_fetch_array($cheeseburger);
$autobus_user = $res['id'];
mysql_close(); //close first connection
$db_host = "khgv";
$db_user = "trdstx";
$db_password = "txz";
$db_database = "gfxx";
mysql_connect($db_host, $db_user, $db_password) or die("Unable to connect to host");
mysql_select_db($db_database) or die( "Unable to select database");
$ASDFASDF = "SELECT * FROM `autobus` WHERE `user_id` = '".$autobus_user."' LIMIT 3";
$BobDoleDontNeedThis = mysql_query($ASDFASDF);
$resnumbatwo = mysql_fetch_array($BobDoleDontNeedThis);
mysql_close(); //close 2nd connection
Am I doing this right? Why is $resnumbatwo returning false?
When using multiple MySQL connections in PHP, you have to supply a fourth argument telling PHP to actually create new connections like this (this is very important, if you are using two connections to the same host):
$db1 = mysql_connect($host1, $user1, $passwd1, true);
$db2 = mysql_connect($host2, $user2, $passwd2, true);
If the fourth argument is not used, and the parameters are the same, then PHP will return the same link and no new connection will be made.
After this you should use "mysql_query" with an extra parameter than defines which connection to use:
$res1 = mysql_query($sql1, $db1) or die(mysql_error($res1));
$res2 = mysql_query($sql2, $db2) or die(mysql_error($res2));
The description of the fourth parameter from php.net is:
"If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The new_link parameter modifies this behavior and makes mysql_connect() always open a new link, even if mysql_connect() was called before with the same parameters. In SQL safe mode, this parameter is ignored."
See more at:
http://www.php.net/manual/en/function.mysql-connect.php
mysql_fetch_array will return false if there are no matching records returned from the query. Please see the following entry from the API reference docs:
Return Values:
Returns an array of strings that corresponds to the fetched row, or
FALSE if there are no more rows. The type of returned array
depends on how result_type is defined. By using MYSQL_BOTH
(default), you'll get an array with both associative and number
indices. Using MYSQL_ASSOC, you only get associative indices (as
mysql_fetch_assoc() works), using MYSQL_NUM, you only get number
indices (as mysql_fetch_row() works).
Better save each connection handler in a variable and transmit it to correspondent mysql_query().
Example:
$dbch1 = mysql_connect($dshost, $dsusername, $dspassword);
$dbch2 = mysql_connect($db_host, $db_user, $db_password);
$cheeseburger = mysql_query($sql, $dbch1);
$BobDoleDontNeedThis = mysql_query($ASDFASDF, $dbch2);
You can use
$dbch1 = mysql_connect($dshost, $dsusername, $dspassword,true);
$dbch2 = mysql_connect($db_host, $db_user, $db_password,true);
$cheeseburger = mysql_query($sql, $dbch1);
$BobDoleDontNeedThis = mysql_query($ASDFASDF, $dbch2);
Using php7
you can use the mysqli_change_user() function.
Like in the examples at the php.net page: http://php.net/manual/en/mysqli.change-user.php
Related
Is there a better solution to store the data in this array and
why is the array empty or at least does not show?
I have this function that connets to a database, it works but I paste it in here for completeness. And to give a complete source (and with your answers a complete solution) for people who have the same problem.
Funktion
<?php
function OpenCon()
{
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "PetName[Birth:day]"; // ;) ;)
$db = "data";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
return $conn;
}
Then I run the funktion
$conn = OpenCon();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {}
And here I try to store 400 random values of the column sent1 from the table sent1
$query = "SELECT sent1 FROM sent1 ORDER BY RAND() LIMIT 400";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) { array_push($sent1, $row["sent1"]);}
print_r($sent1); echo $sent1[rand(0,399)];
btw. I found something interesting I want to share. In each and every answer I read, there was consent that RAND() is very slow.
In this case with a table of 120000 Rows, and 2 columns. If you want to get to get 400 random strings, rand is quicker than other solutions I tried. If you need only one, then there are certainly better solutions.
You need to create the array before you can array_push() to it. Don't you get a warning from your code? I do in some short test code, keeps moaning that it needs an array and I've passed it null.
If you use $sent1[] = $row["sent1"]; instead, it will automatically create the array, and seems to be considered quicker due to not having the overhead of calling a function.
If you're using PDO, you could use fetchAll() instead, to get all the result rows directly into an array. I'm not sure if there's a mysqli equivalent.
This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 8 years ago.
I looked at the other answers to problems similar to mine but cant seem to solve this.
Here is the code.
$connection = mysql_connect("localhost","root","starwars");
$conn = mysql_select_db("project", $connection);
// This code assumes $itemID is set to that of
// the item that was just rated.
// Get all of the user's rating pairs
$sql = "SELECT DISTINCT r.itemID, r2.ratingValue - r.ratingValue
as rating_difference
FROM rating r, rating r2
WHERE r.userID=$userID AND
r2.itemID=$itemID AND
r2.userID=$userID;";
$db_result = mysql_query($sql, $conn);
echo "The result is {$db_result}";
$num_rows = mysql_num_rows($db_result)or die('Cannot Execute:'. mysql_error());
The error being displayed is:
Warning: mysql_query() expects parameter 2 to be resource, boolean
given in C:\xampp\htdocs\recomender\ratingfiles\class.rating.php on
line 177
Line 177 is
$db_result = mysql_query($sql, $conn);
And if I echo $conn it gives the value of "1" which I thought was equal to true, thus boolean, any ideas?
Pass $connection as the second parameter, not $conn.
You assign the result of mysql_select_db to $conn, and mysql_select_db returns true or false, not a connection resource.
This probably means $conn is false, meaning it didnt get setup correctly. You may want to check how you have set that up and ensure the database connection details are correct and the server this is running on can access the database server.
Take a look at the return values on this page:
http://php.net/manual/en/function.mysql-connect.php
change first 2 lines to
$conn = mysql_connect("localhost","root","starwars");
mysql_select_db("project", $conn);
or, better, just refrain from using connection variable at all
mysql_connect("localhost","root","starwars");
mysql_select_db("project");
...
$db_result = mysql_query($sql);
$db_result = mysql_query($sql, $connection);
Second argument to mysql_connect must have
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
http://php.net/manual/en/function.mysql-query.php
I have done a fair bit of research into what i want to do, although i haven't found anything. I am not too sure if i am looking for the right thing :( I am also a little bit new to PHP and MySQL syntax, so please be kind.
I wish to perform the following in this order:
Connect to a database (DONE)
Query for a specific string (I think im done)
From here is gets a bit fuzzy :(
If a match is found for the variable, copy the whole row (I need other variables).
Assign the values from the SQL query to a PHP variables.
From there i will be right to carry on.
I have established the connection to the database with the following:
function connect() {
$dbname = 'database';
$dbuser = 'username';
$dbpass = 'password';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
}
And then calling the function connect();
I then wish to query the database for a particular value, for the sake of this argument i will use a static value. This is what i have:
mysql_select_db(DATABASENAME) or die( "Unable to select database");
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'";
$result=mysql_query($query);
From here i am not too sure how to compare the query result to see if it is a match (something along the lines of mysql rows?).
If there is a match, then i would like to obtain the entire row, and assign each value to a php variable.
I am not asking for you to do it for me, simply i kick in the right direction should be fine!
Hope it explains it enough :)
Thanks for your kind guidance
Ok. You will want to keep the connection to the mysql database somewhere. A common use is $conn.
So you would have
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
Then, either from the URL or Post, or just some variables you have sitting in your php file, you can query the database by putting the variables in the query itself. Also, here you can use $conn so that you have one place to connect to the database, in an include for example, and you won't have to make all of the connection string in each place you need to connect to the DB.
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%" . $varToCompare . "%'";
$result=mysql_query($query,$conn);
Above you are using a like. You may want to just look at doing .. Where column=$var.
Then you can use php to spin through the results into an array (for queries where would get multiple rows).
Where the hell you learned how to use MySQL in PHP ? The mysql_* functions are more then 10 years old and not maintained anymore. Community has already begun to work on deprecating them.
You should be using PDO or MySQLi for that.
// connection to database
$db = new PDO('mysql:host=localhost;dbname=datadump_pwmgr;charset=UTF-8',
'datadump_pwmgr',
'kzddim05xrgl');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// setting up prepared statement for the query
$statement = $db->prepare('SELECT * FROM table WHERE column LIKE :value');
$statement->bindParam(':value', $some_variable, PDO::PARAM_STR, 127);
// executing query and fetching first result
if ( $statement->execute())
{
$data = $statement->fetch(PDO::FETCH_OBJ);
var_dump( $data );
}
This should give you something like what you needed. Though, I would recommend to try this tutorial. And learning more about prepared statements could be useful too.
Also , if you are working with objects, then it is possible to create a single DB connection object , and pass it to multiple other classes to use it:
$pdo = new PDO('sqlite::memory:');
$a = new Foo( $pdo );
$b = new Bar( $pdo, 'something');
This way you pass both objects the same database connection, and you do not need to reinitialize it.
I think you're looking for something like this:
$count = mysql_num_rows($result);
//if there is more then 1 record retrieved from the database
if($count > 0)
{
//Do what ever you want to do here, which I think you want to be
while ($row = mysql_fetch_assoc($result))
{
echo $row["Columnname1"];
echo $row["Columnname2"];
echo $row["Columnname3"];
}
}
else
{
echo "There are no matches for this specific value";
}
You can get the queried data by rows as an associated array using mysql_fetch_array():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_array($data)) !== false)
{
echo "row = $row, name1 = " . $result["name1"] . ", name2 = " . $result["name2"];
$row ++;
}
... or as an objects using mysql_fetch_object():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_object($data)) !== false)
{
echo "row = $row, name1 = $result->name1, name2 = $result->name2";
$row ++;
}
I'm not too sure of what you want, but I can see one probable bug here: you're using LIKE in a way which means =: in order to have LIKE to behave like a like, you need some joker chars :
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'" // This will return all rows where column='VAUL'
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'" // This will return all rows where column='%VAUL%' // This will return any row containing 'VAUL' in column
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE'" // This will return all rows where column='%VAUL' // this will return all rows ending by VAUL. I guess you get it now :)
An to retrieve the actual results:
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'";
$result=mysql_query($query);
while (false !== ($row = mysql_fetch_assoc($result))) {
//here $row is an array containing all the data from your mysql row
}
Try to write the database connection in another page no need to use function and include that page in where ever you need.
ex: require_once 'dbConnect.php';
dbConnect.php consists:
<?php
$dbname = 'datadump_pwmgr';
$dbuser = 'datadump_pwmgr';
$dbpass = 'kzddim05xrgl';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
?>
I'm setting up a blog type page for my business. Brand new to MySQL and PHP. Set up this login system. For some reason have no idea why the login is dropping. Suppose to check for errors then return 'good' through php if the email and password is right. If php returns good then it's suppose to redirect to the blog page.
Been dealing with this for a few months need desperate help please. Thank you.
Here is the php code that goes along with the jquery.
Link to test site is here.
test.toddprod.com/login
Would really appreciated the help.
Thanks
<?php
#fake mysql connection first
DEFINE ('DB_USER','usernamegoeshere');
DEFINE ('DB_PASSWORD','passwordhere');
DEFINE ('DB_HOST','hostnamehere');
DEFINE ('DB_NAME','andtheotherthinghere');
$dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
$db = mysql_select_db(DB_NAME, $dbc) or die('Could not select database.'.mysql_error());
$e = $_POST['email'];
$pass = $_POST['pass'];
$q = 'SELECT user_id from toddprod where email="'.$e.'" and pass= SHA1("'.$pass.'")';
$r = mysql_query($db, $q);
if( mysql_num_rows($r)==1 ){
setcookie ( 'user_id', $r);
setcookie ( 'email', '$e');
setcookie ( 'logged-in', 'true');
echo 'good';
}
else if (mysql_num_rows($r)==0) {
echo 'Your '.$e.' with password '.$pass;
};
mysql_close ($db);
?>
Umm there's a number of things I see wrong here...
First of all your query should be sanitized...
$email = mysql_real_escape_string ($_POST['email']); // escape the email
$pass = SHA1(mysql_real_escape_string ($_POST['pass'])); // escape and encrypt the pass
// now you can put it into the query safely
$query = "SELECT user_id from toddprod where email = '$email' and pass = '$pass' ";
Next you're executing the query wrong, the mysql_query function takes two arguments, the query and the database connection. You're passing the wrong arguments, you're passing the query and the result of the mysql_select_db function which is just a boolean value. So you have to $dbc not $db into that query, and even then you're passing the arguments in the wrong order. The query goes first, than the connection. So it should be...
$result = mysql_query($query, $dbc);
Next you're trying to set the return value from the mysql_query function as your cookie but that value is a resource, not the userid that you need. You have to actually read the value from the resource like this.
$row = mysql_fetch_array($result);
$userid = $row["user_id"];
setcookie('user_id', $userid);
Moving on... when you're setting the email cookie, you have the variable in single quotes, so the cookie will actually contain $e and not the actual email because single quotes store strings litterly (without parsing the variables). So you should either use double quotes, or no quotes at all. So either one of the following is fine...
setcookie('email', "$e");
setcookie('email', $e);
Last but not least, you should not have the semicolon at the end of your if-statement, and you again you need to pass the connection not the database-selection result into the mysql_close function, so it should be
mysql_close($dbc);
There, hope this gets you somewhere, try out these changes and if the problem persists i'd be happy to help you further.
Here are links that will help you out:
http://www.php.net/manual/en/function.mysql-query.php
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Edit:
Here, I have fixed the code according to the problems I found. Try it out, I could not test it so it might have some small syntax errors here and there, but it should give you something to compare with. Also for the future, I would suggest that you name your variables semantically/properly so it's easier for others to pickup and it will also keep you from getting confused like you were passing $db instead of $dbc into a few of your functions.
<?php
// keep the function names in lowercase, no reason, just looks better to me
define('DB_USER', 'usernamegoeshere');
define('DB_PASSWORD', 'passwordhere');
define('DB_HOST', 'hostnamehere');
define('DB_NAME', 'andtheotherthinghere');
// connect to the mysql server
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
// select the database, you don't need to store the result, it just returns true or false
mysql_select_db(DB_NAME, $conn) or die('Could not select database.' .mysql_error());
// escape the input
$email = mysql_real_escape_string($_POST['email']);
$pass = sha1(mysql_real_escape_string($_POST['pass']));
// create the query
$query = "SELECT user_id FROM toddprod WHERE email = '$email' AND pass = '$pass'";
// execute the query
$result = mysql_query($query, $conn);
$usercount = mysql_num_rows($result);
if($usercount == 1){
// read the results and get the user_id
$row = mysql_fetch_array($result);
$userid = $row['user_id'];
// set the cookies
setcookie('user_id', $userid);
setcookie('email', $email);
setcookie('logged-in', 'true');
// echo success message
echo 'good';
}elseif($usercount == 0) {
echo "You're $email with password $pass";
}
mysql_close($conn);
?>
First things first, you MUST sanitise user input with mysql_real_escape_string():
$e = mysql_real_escape_string ($_POST['email']);
$pass = mysql_real_escape_string ($_POST['pass']);
Read up a bit on SQL injection, you'll be very glad you did.
As for the main problem, could you provide a bit more context? How are you checking to see if the user is logged in?
I am working on a project needing me to work with multiple database connections. From what I have read, I should be able to switch between connections in the query itself, something like:
mysql_query("SELECT * FROM user_types", $db_core)or die(mysql_error());
But I receive the error:
Table 'db_company.user_types' doesn't exist
So I can see it is looking at the incorrect db, it is grabbing the last mysql_select_db
I wouldn't want to have to re-select the database everytime but if that is the better way to go I can.
I have the databases selected like so:
<?
$currentpage = $_SERVER["REQUEST_URI"];
//Core DB
$db_core_host = "localhost";
$db_core_username = "root";
$db_core_password = "";
$db_core_name = "db_main";
//
$db_core = mysql_connect($db_core_host,$db_core_username,$db_core_password);
mysql_select_db($db_core_name, $db_core)or die(mysql_error());
//Company DB
$db_company_host = $company['db_server'];
$db_company_username = $company['db_username'];
$db_company_password = $company['db_password'];
$db_company_name = $company['db_name'];
//
$db_company = mysql_connect($db_company_host,$db_company_username,$db_company_password);
mysql_select_db($db_company_name, $db_company)or die(mysql_error());
?>
Not sure if it helps at all but when I echo either of the database connections I get Resource id #5
Use the db.table syntax in the query:
mysql_query("SELECT * FROM databas_ename.table_name", $db_core) or die(mysql_error());
The code you have in your question should work, except when both databases are on the same server. Take a look at the $new_link parameter of mysql_connect (see docs here): if you call it twice with the same server/user/pass, the connection will be re-used - which makes you end up with the mysql_select_db call on one connection influence the other one.
So if you have two different servers, or set $new_link to true, your code should work.