Can someone help me figure out why mysql_query not working?
<?php
$dbhost = "localhost";
$dbusername = "USERNAME";
$dbpassword = "PASSWORD";
$dbname = "DB_NAME";
$connection = mysql_connect($dbhost, $dbusername,$dbpassword) or die('Could not connect');
$db_selected = mysql_select_db($dbname, $connection) or die(mysql_error());
echo " connect... \n";
$result = mysql_query("select * from test",$db_selected);
while($row = mysql_fetch_array($result))
{
echo $i++;
echo "Id : " . $row['Id'] . " Name : " .$row['name'] . " Address : " . $row['address'];
echo "<br>";
}
?>
result:
connect...
You must use $connection instead of $db_connected in your mysql_query. See the man page.
And the fact you did not see the error implies that you have error reporting not configured correctly; check your php.ini and this answer.
It wouldn't have worked anyway since you were fetching a numeric array instead of an associative array (use mysql_fetch_assoc() for that) which is needed by $rec['Id'] syntax (as opposed to $rec[3]).
However, if you are just now beginning with PHP and MySQL, do not use mysql_* functions. They are deprecated and will be soon removed, and you'll have wasted time learning something no longer in use. Use PDO instead. A teensy bit more difficult to master, but lightyears better.
If you want to reference the columns by name you must use mysql_fetch_assoc($result) not mysql_fetch_array($result))
But don't use either. use mysqli_* functions instead or better still pdo.
echo $i++ doesn't produce anything as it is undefined
Related
I rarely do programming. I only know enough to be dangerous as they say and I simply assemble bits of code to get what I want. My code below seems to die at the $sql query statement. It never returns any data. It should show the 13 records that are present, but it says there is none to return. I'm guessing this is some kind of syntax error?
<?php
$host = 'myipaddress';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydatabase';
$conn = mysql_connect($host, $user, $pass, $db) or die("Can not connect." . mysql_error());
// Create connection
//$conn = mysqli_connect($host, $user, $pass, $db);
// Check connection
if (!$conn) {
die("Connection failed: ");
}
$sql = "SELECT * FROM pages WHERE pid > '5'";
$result = mysql_query($conn, $sql);
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
mysql_close($conn);
?>
Your using the mysql_ API right up until you try to fetch rows here, where you're using mysqli_. That will not work.
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
Your script is at risk for SQL Injection Attacks. Please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
EDIT: Your connection (Good Eyes Ralph!) string will not work because mysql_connect() doesn't accept the database as part of the connection. You must use the additional function mysql_select_db() to choose your database.
In addition, it is not necessary to specify the connection link in mysql_query() but if you do it should be the second argument:
$result = mysql_query($sql, $conn);
There is quite a bit wrong with your code.
mysql_connect($host, $user, $pass, $db)
mysql_connect() uses 3 parameters, the 4th doesn't do what you think it does.
http://php.net/manual/en/function.mysql-connect.php
You need to use mysql_select_db() http://php.net/manual/en/function.mysql-select-db.php
Then,
$result = mysql_query($conn, $sql);
The connection comes second in mysql_.
http://php.net/manual/en/function.mysql-query.php
Then you're mixing a MySQLi function mysqli_fetch_assoc which doesn't intermix with the mysql_ library.
Read: Can I mix MySQL APIs in PHP?
So, just use the full MySQLi library
http://php.net/manual/en/book.mysqli.php
or PDO:
http://php.net/manual/en/book.pdo.php
Along with a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
Check for the real errors, should your query fail:
http://php.net/manual/en/function.mysql-error.php
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
As you can see, I did not provide you with a full rewrite, as I feel that in "Teaching a person how to fish...", will feed them for life, rather than "Throwing them a fish...", and only feed them for a day (wink).
You need to use mysql_fetch_assoc() in place of mysqli_fetch_assoc(), because your previous functions are based on mysql_*, not mysqli_*
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
We have the following code in the HTML of one of our webpages. We are trying to display all of the Wifi speeds and GPS locations in our database using the MySQL call and while loop shown in the below PHP code. However, it doesn't return anything to the page. We put echo statements in various parts of the PHP (ex. before the while loop, before the database stuff) and it doesn't even print those statements to the webpage.
<body>
<h2>WiFi Speeds in the System</h2>
<p>Speeds Recorded in the System</p>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbc = mysql_connect($hostname, $username, $password)
or die('Connection Error: ' . mysql_error());
mysql_select_db('createinsertdb', $dbc) or die('DB Selection Error' .mysql_error());
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
$results = mysql_query($data, $dbc);
while ($row = mysql_fetch_array($results)) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
?>
</body>
This line is incorrect, being the AND:
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
^^^
Change that to and using a comma as column selectors:
$data = "(SELECT Wifi_speed, GPS_location FROM Instance)";
However, you should remove the brackets from the query:
$data = "SELECT Wifi_speed, GPS_location FROM Instance";
Read up on SELECT: https://dev.mysql.com/doc/refman/5.0/en/select.html
Using:
$results = mysql_query($data, $dbc) or die(mysql_error());
would have signaled the syntax error. Yet you should use it during testing to see if there are in fact errors in your query.
Sidenote:
AND is used for a WHERE clause in a SELECT.
I.e.:
SELECT col FROM table WHERE col_x = 'something' AND col_y = 'something_else'
Or for UPDATE, i.e.:
UPDATE table SET col_x='$var1'
WHERE col_y='$var2'
AND col_z='$var3'
Footnotes:
Consider moving to mysqli with prepared statements, or PDO with prepared statements, as mysql_ functions are deprecated and will be removed from future PHP releases.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
"Thank you for the suggest but we tried that and it didn't change anything. – sichen"
You may find that you may not be able to use those functions after all. If that is the case, then you will need to switch over to either mysqli_ or PDO.
References:
MySQLi: http://php.net/manual/en/book.mysqli.php
PDO: http://php.net/manual/en/ref.pdo-mysql.php
hi mate i see some problem with your DB connection & query
here is example check this out
in SELECT is incorrect, being the AND .using a comma as column selectors:
and make condition for after set query & check data validation that is proper method
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "createinsertdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT `Wifi_speed `, `GPS_location `, FROM `Instance`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
} else {
echo "0 results";
}
$conn->close();
?>
I am trying to get my head round mysqli so i can update my site and make it more secure. I have an article in a database and I am trying to echo it out like i would with mysql. I have seen loads and loads of posts here about basic mysqli but cannot find a way to get this to work. So i apologize if i have asked a question that has already been asked but what i have so far is mainly a result of what I have found here.
I am getting the following error:
Fatal error: Cannot use object of type mysqli_result as array in C:\xampp\htdocs\workshop\msqli-test.php on line 20
Here is the code i have so far:
<?php
$DBServer = 'localhost';
$DBUser = 'root';
$DBPass = 'pass';
$DBName = 'test_db';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$sql='SELECT * FROM articles WHERE title = "Simple Ideas For Your Website Logo."';
$row=$conn->query($sql);
echo "<div class='articlepreviewlayoutreadmore'><a href='".$row['link']."'>Read Full Article</a></div>";
echo "<img src='".$row['images']."' />";
echo "<h3><a href='".$row['link']."'>";
echo $row['title']."</a></h3>";
echo "<h6>Author: ".$row['author']."</h6>";
echo "<h6>Published:".$row['timestamp']."</h6>";
echo "<p>".$row['content']."</p>";
echo "<div class='articlepreviewlayoutreadmore'><a href='".$row['link']."'>Read Full Article</a></div>";
?>
Thanks in advance for any help with this, i am getting old and keeping up to date with programming languages gets harder year after year.
You've missed a step. After you execute your query you get a result object returned. You then need to use that to get your results:
$sql='SELECT * FROM articles WHERE title = "Simple Ideas For Your Website Logo."';
$result = $conn->query($sql);
$row = $result->fetch_assoc();
I'm trying to access and read a view from a MS SQL database with PHP. For now I'm just trying to echo out the results on the screen. When I test, my page shows nothing at all.
This is what I have:
<?php
$myServer = "localhost";
$myUser = "username1";
$myPass = "password1";
$myDB = "database1";
//connect to database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select database
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//declare statement
$query = "SELECT ProductId";
$query .= "FROM Inventory ";
$query .= "WHERE UPC='15813658428' and ManufacturerID=465";
//execute the query
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display results
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["id"] . $row["name"] . $row["year"] . "</li>";
}
//close
mssql_close($dbhandle);
?>
Often when you get a completely blank output from PHP, it is because the server encountered a problem when parsing or interpetting your code. The best way to deal with this when you are getting no other errors is to strip out (or comment out) large blocks of your code and to use numeric echo statements to verify that the code you have not stripped out is executing. Then slowly add more and more of the code back in.
In this specific case, I am guessing that the problem may come down to the spaces after the ?> in your php file. That can confuse servers. Try removing the ?> completely.
If that still results in no output, then comment out everything after $myDB = "database1";, add an echo statement right before the commenting, and slowly move code back into the uncommented section until you find the line that causes the problem.
I need start using the mysqli extension but I'm finding all kinds of conflicting info depending on how all the info is that I'm trying to use.
For example, my header connects to a 'config.php' file that currently looks like this:
<?php
$hostname_em = "localhost";
$database_em = "test";
$username_em = "user";
$password_em = "pass";
$em = mysql_pconnect($hostname_em, $username_em, $password_em) or trigger_error(mysql_error(),E_USER_ERROR);
?>
But when I go to php.net I see that I should be using this but after updating everything I get no database.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
?>
I also went through and added an "i" to the following code in my site and again no luck:
mysql_select_db($database_em, $em);
$query_getReview =
"SELECT
reviews.title,
reviews.cover_art,
reviews.blog_entry,
reviews.rating,
reviews.published,
reviews.updated,
artists.artists_name,
contributors.contributors_name,
contributors.contributors_photo,
contributors.contributors_popup,
categories_name
FROM
reviews
JOIN artists ON artists.id = reviews.artistid
JOIN contributors ON contributors.id = reviews.contributorid
JOIN categories ON categories.id = reviews.categoryid
ORDER BY reviews.updated DESC LIMIT 3";
$getReview = mysql_query($query_getReview, $em) or die(mysql_error());
$row_getReview = mysql_fetch_assoc($getReview);
$totalRows_getReview = mysql_num_rows($getReview);
And here's the only place on my display page that even mentions mysql so far:
<?php } while ($row_getReview = mysql_fetch_assoc($getReview)); ?>
I did see something at oracle that another stackoverflow answer pointed someone to that updates this stuff automagically, but I have so little code at this point it seems like overkill.
Adding an i to any mysql function won't make it a valid mysqli function. Even if such function exists, maybe the parameteres are different. Take a look here http://php.net/manual/en/book.mysqli.php and take some time to check mysqli functions. Maybe try some examples to become familiar with the way things work. I also reccomend you to choose either object oriented code, either procedural. Don't mix them.
I just made the switch to mysqli lately, took me a few hours to wrap my head around it. It works well for me, hope it will help you out a bit.
Here the function to connect to the BD:
function sql_conn(){
$sql_host = "localhost";
$sql_user = "test";
$sql_pass = "pass";
$sql_name = "test";
$sql_conn = new mysqli($sql_host, $sql_user, $sql_pass, $sql_name);
if ($sql_conn->connect_errno) error_log ("Failed to connect to MySQL: (" . $sql_conn->connect_errno . ") " . $sql_conn->connect_error);
return $sql_conn;
}
This will return a Mysqli Object that you can use to make you request afterward. You can put it in your config.php and include it or add it at the top of your file, whatever works the best for you.
Once you have this object, you can use it to make your query against the object like so: (in this case, if an error came up it will be outputted in the error_log. I like having it there, you can echo it instead.
//Use the above function to create the mysqli object.
var $mysqli = sql_conn();
//Create the query string (truncated for the example)
var $query = "SELECT reviews.titl ... ... ted DESC LIMIT 3";
//Launch the query on the mysqli object using the query() method
if(!($results = $mysqli->query($query))){
//It it fails, log the error
error_log(mysqli_error($mysqli));
}else{
//Manipulate your data.
//here it depends on what you retunr, a single value, row or a list of rows.
//Example for a set of rows
while ($record = $results->fetch_object()){
array_push($array, $record);
}
}
//Just to show, this will output the array:
print_r($array);
//Close the connection:
$mysqli->close();
So basically, in mysqli, you create an object and use the method to work your way out.
Hope this helps. Once you figured it out, you will most likely enjoy mysqli more that mysql. I did anyway.
PS: Please note that this was copy/pasted from existing, working code. Might have some typo, and might forgot to change a var somewhere, but it's to give you an idea of how mysqli works. Hope this helps.