PHP get data from DB not working [duplicate] - php

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
Can you figure out my code? All the code does is: No database selected It won't get the data from the db. The server os is Ubuntu or OS X. I been pulling my hair out for hours.
<?php
mysqli_connect("localhost", "root", "");
mysql_select_db("hit-counter");
$sql_get_count = mysql_query("SELECT id FROM hit_info ORDER BY id DESC LIMIT 1");
if($sql_get_count === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_assoc($sql_get_count)) {
print_r($row);
}
?>
I try this, it does the same
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("hit-counter");
$sql_get_count = mysql_query("SELECT id FROM hit_info ORDER BY id DESC LIMIT 1");
if($sql_get_count === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_assoc($sql_get_count)) {
print_r($row);
}
?>

you have an error in your code. You use mysqli_ function to connect the server but you use a deprecated function mysql_ to select the database.
Try this code:
mysqli_connect("localhost", "root", "");
mysqli_select_db("hit-counter");
Another option when using mysqli_ is to select the database you want during connecting to the server:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");

You didn't mention database name:try this
<?php
$con = mysqli_connect("127.0.0.1","root","654321","testV2") or die("Some error occurred during connection " . mysqli_error($con));
// Write query
$strSQL = "SELECT id FROM did ORDER BY id DESC LIMIT 1";
// Execute the query.
$query = mysqli_query($con, $strSQL);
while($result = mysqli_fetch_array($query))
{
echo $result["id"]."
";
}
// Close the connection
mysqli_close($con);
?>

You cannot interchange the mysql and mysqli functions, please modify your mysql_select_db to mysqli_select_db.

I will not go over the errors everyone else has pointed out. But, I will mention one that no one has. I think the - character in your database name will also cause problems. You should enclose the database name in back ticks. The back tick is this ` character, most likely the far left key above the TAB key. If you had error reporting turned on, or looked at your php error log, you would have seen the error.

Related

Get result of a mysql query

I have a pretty basic website connected to a database and I want to access the result of an SQL query:
$connection = mysql_connect("localhost", "username", "password")
or die(mysql_error());
mysql_select_db("Database")
or die(mysql_error());
$query = mysql_query("SELECT path FROM db1 WHERE id > 4");
while($row = mysql_fetch_object($query))
{
echo $row->path;
}
On the website nothing shows, not even an error
(The SQL code works for sure)
Since you stated in comments that there were no id greater than 4,
you could have just done WHERE id >= 4 which means greater than or equal to 4 and you would have had results.
References:
http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html
http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_greater-than-or-equal

Get a row from a database based on querystring

BIt of a php/mysql noob here, hope someone can help.
Ok so i have a URL which has an id in the querystring like so: wwww.mysite.com/page1.php?id=1
What i want to do is connect to a table in the database and get the data from the columns on one row where the first column named ID equals the id number held in the querystring.
I then want to print the data from each column in different div's elsewhere on the page.
There's also the additional issue of what to do if there's no row in the table with the same id as the querystring, i'd want it to change the id in the querystring to 1 and load that rows data.
I had a little go, i know it connects ok but i have no idea if the rest is what i want:
<?php
$link = mysql_connect('Address', 'Database', 'Password');
if (!$link) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = "select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per=".$_GET['ID']."";
echo $result['A'];
mysql_close($link);
?>
And then put this in the div's to print the data.
<?php echo $result['A']; ?>
Am i along the right lines or completely wrong?
$dbConnection = mysql_connect('Address', 'Database', 'Password');
if (!$dbConnection) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = $dbConnection->prepare("select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per = ?");
$query->bind_param('s', $per);
$query->execute();
$result = $query->get_result();
<?php echo $result; ?>
use this code first to avoid SQL Injection second that's the way it should work in PHP first prepare the query second execute and only then show it.
Use mysql_query function in your code.
mysql_* functions is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
<?php
$link = mysql_connect('Address', 'Database', 'Password');
if (!$link) {
die('Could not connect to MYSQL database: ' . mysql_error());
}
$per = $_GET['id'];
$query = "select A,B,C,D,E,F,G,H,I,J,K,L from table_name where per=$per";
$result = mysql_query($query, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['A'];
mysql_close($link);
?>

Cannot fetching data with php in Linux

I want to connect to a database and fetch data , But I can't do that . Would you mind helping me what is the problem ? By the way I use Linux Ubuntu. Here is the code and info :
<?php
// DB name : db
// Table name : users
// Columns : username , password
mysql_connect("localhost" "root" "root") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$query = mysql_query("SELECT * FROM users") or die(mysql_error());
$fetch = mysql_fetch_array($query);
echo "Username :".$fetch['username'];
echo "Password :".$fetch['password'];
mysql_close();
?>
You forgot to separate the variables on your mysql_connect statement. Do like this
mysql_connect("localhost", "root", "root") or die(mysql_error());
------^ -----^ // Added commas here
Do it like this:
while ($fetch = mysql_fetch_array($query, MYSQL_ASSOC)) {
echo "Username :".$fetch['username'];
echo "Password :".$fetch['password'];
}
Migrating to MySQLi from mysql_*, read here
Most importantly, stop using mysql_* functions as they are deprecated. Switch to MySQLi or PDO.

record won't delete from database

I am trying to delete a record using php from a database. This is supposed to happen when I click a button, no error is displayed and the query appears on the screen but the record remains on the database
phpmyadmin gives me the following code to use: DELETE FROM 'the shop'.'customer' WHERE 'customer'.'CustomerID' = 8
<?php
$host="localhost"; // Host name
$tbl_name="customer"; // Table name
$db_user="root";
$db_pass="";
$connect = mysql_connect("$host", "$db_user", "$db_pass");
$db_name="the_shop"; // Database name
mysql_select_db("$db_name");
if (!$connect)
{
die("MySQL could not connect!");
}
if(isset($_GET['submit2'])){
$db_username = $_GET['username'];
$sql4 = "DELETE FROM 'the_shop'.'customer' WHERE 'customer'.'CustomerID' = 8"
or die('error deleting record');
mysql_query($sql4);
echo $sql4;
}
?>
I know this will only delete the record that has a CustomerID that = 8
my intention is that once this works I will replace CustomerID with Username and the '8' with the relevant variable that will be given a value via a form
any help is appreciated
You are using quotes instead of back tick
$sql4 = "DELETE FROM `the_shop`.`customer` WHERE `customer`.`CustomerID` = 8";
Moreover you don't need back ticks(In this case as you are not using any Reserved keywords here) as well as you are using die() at wrong place
Use this,It is working.
<?php
$host="localhost"; // Host name
$tbl_name="customer"; // Table name
$db_user="root";
$db_pass="";
$connect = mysql_connect("$host", "$db_user", "$db_pass");
$db_name="the_shop"; // Database name
mysql_select_db("$db_name",$connect);
if (!$connect)
{
die("MySQL could not connect!");
}
if(isset($_GET['submit2'])){
$db_username = $_GET['username'];
$sql4 = "DELETE FROM `the_shop`.`customer` WHERE `customer`.`CustomerID` = 8";
mysql_query($sql4,$connect) or die('error deleting record');
echo $sql4;
}
?>
Your statement is not correct. You use quoted instead of back ticks. But you can make your statement easier.
$sql4 = "DELETE FROM customer WHERE CustomerID = 8";
$sql4 = "DELETE FROM `the_shop`.`customer` WHERE `customer`.`CustomerID` = 8"
mysql_query($sql4);or die('error deleting record');
echo $sql4;
You don't need to specify which database to query in your query.
This will suffice:
DELETE FROM customer WHERE CustomerID = 8
The Mysql extension is deprecated. This means that it is no longer supported by PHP and should not be used. Try mysqli or pdo instead.
You can just use this. There is no need for you to specify the database.
delete from customer where CustomerID = 8

PHP/MYSQL Update query not working

Can anyone tell my why this update query is not working?
if ($_GET['update']) {
include 'config.php';
//Connect to MYSQL Database server
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Could not connect to MYSQL Database.");
$result = mysql_select_db(DB_NAME, $connect) or die("Could not connect to MYSQL table.");
mysql_query("UPDATE contact SET read = 1 WHERE id = '$_GET[update]'")or die("Query failed.");
echo "Update works!";
} else {
echo "Update does not work...ughh.";
}
Thank you in advance.
Edit: I got the query to work. For anyone who was worrying about the security, I was using this script as a test to see if I wanted to use it. I just added the security now that the script works. Thank you all for the help and tips.
What is column read?
mysql_query("UPDATE contact SET read = 1 WHERE id = '$_GET[update]'")
Judging by the non-capitalization of read, I suspect you are using a reserved word in MySQL for that column.
See:
Reserved Words in MySQL
To Get around this, just put a single quote around read. I.E.
mysql_query("UPDATE contact SET 'read' = 1 WHERE id = '$_GET[update]'")
Or better per j.bruni:
mysql_query("UPDATE contact SET `read` = 1 WHERE id = '$_GET[update]'")
Try this for your query line:
mysql_query("UPDATE contact SET read = 1 WHERE id = '".$_GET[update]."'")or die("Query failed: " . mysql_error());
Notice the change of the die() statement for better error handling:
die("Query failed: " . mysql_error());
*Also, just an FYI, you should really escape user variables (e.g. GET variables) like so to prevent SQL injections:
mysql_query("UPDATE contact SET read = 1 WHERE id = '".mysql_real_escape_string($_GET[update])."'")or die("Query failed: " . mysql_error());
Please report back the result.
I believe you need to escape the string to have $_GET['update'] to add it's value to the string. But you really should be using prepared statements least you be attacked by malicious users.
Prepared Statements: http://php.net/manual/en/pdo.prepared-statements.php
READ is a reserved word. You need to put it within backticks or rename your field.
Take a look at this link:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You can test so
mysql_query("UPDATE contact SET read = 1 WHERE id = '".(int)$_GET['update']."'")or die("Query failed.");
if isn't this the problem specific
mysql_query("UPDATE contact SET read = 1 WHERE id = '.$_GET[update].'")or die("Query failed.");
echo "Update works!
Please try to not use the mysql_query. It's old and it's not efficient. why don't try to learn about the PDO and prepare statements .. ?

Categories