I am attempting to create new tables every time I post to this method, but for some reason I can not figure out why it dies.
<?php
$host = "127.0.0.1";
$username = 'cotten3128';
$pwd = 'pwd';
$database = "student_cotten3128";
$pin = $_REQUEST['pinSent'];
$words = $_REQUEST['resultSent'];
$tableName = $pin;
$db = new mysqli($host, $username, $pwd, $database);
if ($sql = $db->prepare("CREATE TABLE $pin (id INT(11) AUTO_INCREMENT);")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die('Could not create table');
}
for($i=0;$i<count($words);$i++){
if($sql = $db->prepare("INSERT INTO ".$pin.$words[$i].";")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die("Could not add data to table");
}
}
mysqli_close();
?>
Any help or insight would be greatly appreciated.
The intention of my post is to help you finding the issue by yourself. As you did not added much information I assume my post is helpful for you.
Based on the code you have shared I guess you mean one of your called die() functions is executed.
Wrong function call
As Jay Blancherd mentioned mysql_close is the wrong function. You rather have to use mysqli_close as you created a mysqli instance.
Beside of that mysql_* is deprecated and should not be used anymore.
Debugging Steps
Not only for this case but in general you should ask yourself:
Is there an error message available? (Frontend output, error log file, ...)
YES:
What's the message about?
Is it an error you can search for? E.g. via a search engine or the corresponding documentation?
Look up in the bug tracker (if available), by the software developer of the software you are using, and if it has not been reported yet report the issue.
NO: (if none error message available OR you cannot search for it as it is a custom error message)
Search in the files of the software you are using for the error message and start a core-debugging.
STILL NO SOLUTION?:
Ask on stackoverflow.com e.g. and tell your issue and the steps you have performed to find and fix the bug. Post only as much code as necessary plus use a proper format.
Debugging in your case:
In order to narrow down the scope. Which of the die() is executed? Depending on that echo the query to execute just before it actually is executed. Then copy the SQL query to an SQL editor and look at it syntax. After that you probably know the problem already.
Related
I have a small problem. I'm trying to make a simple register/login system with sessions and I got this error:
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\members\includes\login.inc.php on line 9
This is the relevant line of code:
$result = $conn->query($sql);
The first time I tried it was working.
The rest of the code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$email = $_POST['email'];
$password = md5($_POST['password']);
$sql = "SELECT email, password FROM member WHERE email = '$email' AND password = '$password'";
$result = $conn->query($sql);
I also have db.php, which is used to connect the MYSQL and everything inside it is fine.
I cannot understand why, the first time I tried it was working I guess and now this kind of error.
I'm also having the db.php which is used to connect the MYSQL and everything inside is fine.. could someone explain me why I keep facing this error ?
I'm going to speculate. I'm speculating that you have a separate file (probably called db.php) which "handles" the setting up of the database connection. I'm further going to speculate that you've a chain of files which are require() (or include())'d into your web app.
I've seen this more times than I care to recall. It's a very old fashioned way of separating code into logical chunks inside PHP - which needs to be left in the past.
I'm speculating that you were previously defining $conn in another script which was included (or required) before this code. A global variable, which had was dependency later in the code execution. Invisible to the file it was declared in.
That's the problem. The quick/hack fix is to rename $conn or the restore the original declaration of it and make sure it's global and make sure it is included before this code is ran.
The proper fix (IMHO) is to look at using a framework (Laravel, Lumen, CodeIgniter, Yii, there are many - take your pick) and read up on the topics of dependency injection, autoloading and namespacing. Think about why global variable declarations make for unmaintainable code.
If you're really reluctant to go with a full framework, at the very least have a look at some database-abstraction libraries like doctrine (and it's sub-library dbal) which can easily be auto-loaded into your project via composer.
As Sascha already pointed out, $conn might be either not defined at all, or it's not an object (hence the error message).
From the code sample you have provided, it's actually a bit hard to tell what kind of connection object you might be using, but I think it's save to say that in your case it might be either PDO or mysqli.
For the sake of simplicity, let's stick with mysqli. A working code sample based on mysqli would look like this (shortened example taken from the docs cited above):
$conn = new mysqli("localhost", "my_user", "my_password", "world");
$result = $conn->query($sql);
Though you really should go for so-called prepared statements, as your code right now is prone to SQL injection as wally already stated.
I would have linked wally's answer and provide you with a link to the PHP docs relating to prepared statements, but apparently, my lack of reputation points don't allow me to, so just do a quick Google search for PHP & prepared statements.
The database connection file has to be added at the beginning of the file.
The present format is easy.
<?php $mysqli = new mysqli("localhost", "Userid", "password", "database name"); if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; }
?>
At the beginningļ¼
require 'db.php';
$conn = new db();
I have a simple form that needs a list of stops in the textarea and returns an id for each on the right hand side. This is my screenshot on localhost...I have the same table names, column names, number of records on both localhost and live server.
Here's the screenshot of the same page with same query on live server...
Here's the code I am using on both pages
$conn = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
if(isset($_POST["busnumber"], $_POST["busroute"])){
$stops = explode(PHP_EOL, $_POST["busroute"]);
$sql = 'SELECT * FROM stops WHERE stop_name LIKE :stop';
$statement = $conn->prepare($sql);
$statement->setFetchMode(PDO::FETCH_ASSOC);
foreach($stops as $stop){
$statement->bindValue(':stop', $stop);
$statement->execute();
$results = $statement->fetchAll();
foreach($results as $result){
echo $result['stop_id'].' '.$result['stop_name']."</br>";
}
}
}
As you can see, it returns the ID of the last row only on the live server. Can someone please tell me how this is possible and what I am missing?
EDIT 1
Notice what happens when I reverse the data entered in the text area
The localhost shows both the ids now
Guess what the server shows after reversing? Only the LAST ROW!
You don't need setFetchMode(). In the time I've used PDO I always had the best results with just using bindParam() and fetch() with the most default setup of PDO, which means just setting the errormode to exception and charset to utf8 like this:
try
{
$con = new PDO("mysql:host=".$host.";dbname=".$db_name, $user, $password);
}
catch(PDOException $e){
die("ERROR ". $e->getMessage());
}
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->exec("SET NAMES utf8");
Fetching any results like this
while($r = $statement->fetch())
{
echo $r['id'];
}
Any time when someone has used a different set up, I've noticed they've faced problems.
Try this, perhaps.
This is very simple. Please check your live db via phpmyadmin if you have access and from phpmyadmin run your queries like you are running it from php code. May be you have some restrictions of mysql or php on live. And also check your db versions on localhost and live with php versions too. Let me know the results of phpmyadmin queries thanks!
Just guessing the problem. I don't really think if this answer is correct. So please pardon me in advance.
PDOStatement::fetchAll() returns an array that consists of all the rows returned by the query. From this fact we can make two conclusions:
This function should not be used, if many rows has been selected. In
such a case conventional while loop ave to be used, fetching rows
one by one instead of getting them all into array at once. "Many"
means more than it is suitable to be shown on the average web page.
This function is mostly useful in a modern web application that
never outputs data right away during fetching, but rather passes it
to template.
Source: PDO Tutorial
I FIXED the error. I have answered it in detail on a different post and I am linking to that post from HERE Thank you all for your time and answers
i am having difficulty with connecting my database to mysql, i have tried many different ways of trying to get it to connect to my database, but none these methods seem to work. I am only new to php and i could be missing something, but i dont know what it is.
This is for a search engine, i have the form created.
I would think that my problem is coming from this line of code, mysql_connect("localhost", "root", "") or die("could not connect");?!
I was wondering if i could be told what is the problem and how to fix it, thank you so much.
here is my code below.
<?php
//connect
mysql_connect("localhost", "root", "") or die("could not connect");
mysql_select_db("search") or die("could not find database");
$output = '';
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","", $searchq);
$query = mysql_query("SELECT * FROM gp management system WHERE Title LIKE '%$searchq%' OR Description LIKE '%$searchq%' OR Keyword LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
}
else{
while($row = mysql_fetch_array($query)) {
$Title = $row['Title'];
$Description = $row['Description'];
$Keyword = $row['Keyword'];
$output .= '<div> ' .$Keyword. ' </div> ';
}
}
}
?>
SQL errors:
SELECT * FROM gp management system WHERE Title...
^^-- table name
^^^^^^^^^^ aliasing 'gp' as 'management'
^^^^^^-- extra unknown garbage
Table names shouldn't have spaces to begin with, but if you insist on having them, then you need proper quoting:
SELECT * FROM `gp management system` etc...
^--------------------^
Never output a fixed/useless "could not search" error. Have the DB tell you what went wrong:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^^
As your only new, you really should stop using mysql_ and change to mysqli_ or (my preference) PDO(). Your message in your title seems to be coming from your selectdb line, so you're actually connecting to the database fine, it's just not able to locate the schema that you are trying to use (i.e. "search" does not exist as a schema name in your DB environment). Unless that's not the error that you are getting, in which case it's a flaw in your actual SQL query. Without an accurate statement of what you are getting back on the screen when you try to run the script then not much can be done to help.
I would rather do somehow like I did ages ago, see below:
function db_connect($host, $username, $passwd, $db_name) {
$db = mysql_connect($host, $username, $passwd);
if (!$db) {
echo "Login to database failed: ";
echo mysql_error();
return false;
}
$result=mysql_select_db($db_name); //Select the database
if (!$result) {
echo "Cannot find the database: ".$db_name;
echo mysql_error();
return false;
}
return $db; //Database descriptor
}
However you shouldnt rely on the old MYSQL extension, but use MYSQLi.
EDIT: as #tadman pointed out there were a # sign infront the mysql_connect call, however there is an if statement for checking and a call to error output.
As others have said, your code is something of a mess - you seem to be new to programming, not just in PHP. But everyone has to start somewhere, so....
You might want to start by learning a bit about how to ask questions - specifically you have included a lot of code which is not relevant to the problem you are asking about - which is about connecting to MySQL. OTOH you have omitted lots of important information like the operating system this is running on and what diagnostics you have attempted. See here for a better (though far from exemplary example).
Do read your question carefully - the title implies an issue with mysql_select_db() while in the body of the content you say you think the problerm is with mysql_connect(). If you had provided the actual output of the script we would have been able to tell for ourselves.
You should be checking that MySQL is actually running - how you do that depends on your OS. You should try connecting using a different client (the mysql command line client, sqldeveloper, Tora, PHPMyAdmin....there are lots to choose from).
You should also check (again this is operating system specific) that your MySQL instance is running on the same port as is configured in your php.ini (or overridden in your mysql_connect() call).
MySQL treats 'localhost' as something different from 127.0.0.1 on Unix/Linux systems. If this applies to you try 127.0.0.1 in place of localhost.
or die("could not connect");
Does not help in diagnosing the problem. If instead you...
or die(mysql_error());
You will get a more meaningful response.
BTW: while writing code using the mysql extension rather than mysqli or PDO is forgivable, I am somewhat alarmed to see what appears to be medical information managed with no real security.
I am using a PHP PDO driver for an application that uses Apache Cassandra and I cannot fetch the information I need. Is anything obviously wrong?
$db = new PDO('cassandra:host=localhost;port=9160');
$db->exec("USE project");
$st = $db->prepare("SELECT fname FROM users WHERE email=:em;");
$st->bindValue(':em', 'email1#gmail.com', PDO::PARAM_STR);
$st->execute();
print_r($st->fetch(PDO::FETCH_ASSOC));
Nothing is printed to the window. The table users was created with the email column as the primary key. I had no trouble inserting and updating information to the users table in my app, but still cannot figure out how to fetch single values successfully. Similarly, when I fetchAll() with some query I can print the arrays (rows) to the screen but cannot index them to grab specific values. Maybe there is some detail about cassandra that I am missing?
Do the following:
Check the return values of each method.
Check if there is an error after executing the statement.
Check the error log of your php interpreter.
$db = new PDO('cassandra:host=localhost;port=9160');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$db->exec("USE project");
$st = $db->prepare("SELECT fname FROM users WHERE email=:em;");
if ($st == false) {
print_r($db->errorInfo())
exit;
}
if ($st->bindValue(':em', 'email1#gmail.com', PDO::PARAM_STR) == false) {
print_r($db->errorInfo())
exit;
}
if ($st->execute() == false) {
print_r($db->errorInfo())
exit;
}
print_r($st->fetch(PDO::FETCH_ASSOC));
I had a similar problem. I used YACassandraPDO. Unfortunately when use it with php 5.4 I get error 502. Decided to write his or her library that allowed to work with Cassandra binary protocol without experiencing similar problems.
In the future, I plan to speed it up.
Maybe it will help you. Syntax like PDO.
As part of a PHP web application, I'm querying a MySQL database using mysqli and prepared statements.
I've used exactly the same code on a few queries and it works, but on one particular query, it always returns an empty record set. I've run exactly the same query from the MySQL command line, and it correctly returns the result. I've checked the parameters being passed in, and they're fine.
I've spent the best part of a day trying to figure out why I'm always getting an empty record set with no errors or warnings. I've got PHP's errors set to display on the page, and I've got them set to E_ALL|E_STRICT. I still don't get any warnings or errors.
I've tried all the obvious things, like making sure I can actually connect to the database, checking the parameters that are being passed in, and making sure the row I'm trying to return actually exists in the database. I've had var_dump()s and die()s all over the page to check what's coming back, and it's always a legitimate, but empty, recordset.
function salt() {
return("I've removed my salt from this sample code");
}
function openDatabase() {
$conn = new mysqli("127.0.0.1", "username", "password", "database")
or die("Error: Could not connect to database.");
return($conn);
}
function checkUserCredentials($username, $password) {
$goodPassword = md5(salt().$username.$password);
$conn = openDatabase();
$query = $conn->stmt_init();
$query->prepare("SELECT id FROM users WHERE email = ? AND passwordHash = ?")
or die('Problem with query');
$query->bind_param("ss", $username, $goodPassword)
or die('Error binding parameters');
$query->execute() or die("Could not execute");
$query->bind_result($col1) or die ("Could not bind result");
if ($col1 !== 0) {
die("Authentication Complete");
} else {
die("Authentication Failure! Number of Rows: ".$query->num_rows." Username: " . $username . " Password Hash: " . $goodPassword);
}
}
Any feedback is appreciated. I'm sure I'm missing something simple, but if I didn't shave my head I'd be tearing my hair out right now.
Thanks
I'm not familiar with the mysqli library (I usually use PDO which provides a very similar cross platform API) so I can't immediately see any problem. However, you might try watching the mysqld log. See here for info:
http://dev.mysql.com/doc/refman/5.1/en/query-log.html
By tailing the log, you should be able to see the exact query that was submitted.
One final note, I notice you're using a fixed salt value. Wouldn't it be better to generate this value randomly each time you need it and then store it in the users table? Generally, a salt is not intended to be secret, it's just there to prevent people precomputing tables of passwords using the hash algorithm that you use.
In case anyone else runs into similar issues, it really helps if you run fetch() on your mysqli_stmt object.
In my code above, the solution looks like this:
$query->bind_result($col1) or die ("Could not bind result");
$query->fetch(); // <--- How could I forget to do this?
if ($col1 !== 0) {
return true;
} else {
return false;
}
Added on behalf of OP