Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Hello there im new in php, im trying to make a news plugin on my website. But i have following error which i cant get fixed.
$query = "SELECT `id` , `headline`, `timestamp` FROM `news` ORDER BY `timestamp` DESC";
$result = #mysql_query($query);
if(!$result){
echo('Error selecting news: ' . mysql_error());
exit();
}
if (mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_object($result))
{
?>
<font size="-1"><b><? echo $row[headling]; ?></b> <i><? echo formatDate($row[timestamp]); ?></i></font><?
}
}
mysql_close($conn);
?>
Im geting same error over and over again.
Error: Error selecting news: No database selected
you need to select a database.
see mysql_select_db http://php.net/manual/de/function.mysql-select-db.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Connection failed : ' . mysql_error());
}
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Db does not exist : ' . mysql_error());
}
?>
Also note that mysql_* is deprecated. use new php style like
http://php.net/manual/de/mysqli.select-db.php
Database in this example is "test"
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
I'm guessing you need to specify which database you're attempting to query in your statement.
select a.id , a.headline, a.timestamp
from database.news a
order by a.timestamp desc
Replace "database" above with the name of yours.
Related
This question already has answers here:
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
I'm just putting a simple PHP program together that simply counts the number of total rows in my database and returns the result as a JSON object when it recieves a get request from my frontend.
This should all be super simple but for the life of me I can't figure out how to retrieve the count result in a usable format. All I get from this is "null"
any ideas?
$con = mysqli_connect($servername, $username, $password, $dbname);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$query="SELECT COUNT(*) FROM database";
$result = mysqli_query($con,$query);
$count = mysqli_fetch_assoc($result);
echo json_encode($count);
You can use COUNT as to avoid a very long key.
Here's a code example
$sql = "SELECT COUNT(column) as count FROM mytable";
$stmt = mysqli_stmt_init($db);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_fetch_assoc($result)['count'];
echo $count;
To display data in JSON you can try this:
echo json_encode(['count' => $count])
That by itself will not give you the count.
I would suggest that you start using MySQL object methods instead of functions.
You should also use the "as" satement as way to give a name to the column that has the count value; in my example that column will be known as C .
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT COUNT(*) as C FROM database";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
$row = $result->fetch_assoc();
echo $row["C"];
}
EDIT:
In the specific case of SELECT COUNT you'll only get 1 row, so for this specific example you could do just fetch_assoc().
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am not able to fetch data from a temporary table that I have just created with a SELECT statement off another table.
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
$query = "create temporary table temp1 select name from trn_games";
$query2 = "select name from temp1";
$result = mysqli_query($link, $query2) or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
echo $row['name'];
}
Note: To create a table by SQL Query you should execute it by mysqli_query($link, $query);.
You only write SQL Query but do not execute it.
$query = "create temporary table temp1 select name from trn_games";
$execute = mysqli_query($link, $query); // here execute your SQL QUERY.
$query2 = "select name from temp1";
$result = mysqli_query($link, $query2);
while($row = mysqli_fetch_array($result)) {
echo $row['name'];
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am doing a project with PHP and MySQL. I have this problem.
This is my code
<?php
$proyecto = $_POST['id'];
$servername = "localhost";
$username = "dbuser";
$password = "dbpass";
$dbname = "proyectos";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `horas`, `trabajador` FROM `horas` WHERE `proyecto` LIKE '$proyecto' ";
$result = $conn->query($sql);
$conn->close();
?>
It takes a parameter from a post request and do a search in the database database looks like this:
So I want to get as result the sum of all the hours (horas column) that are made by the same worker (trabajador column). Example of result:
Prueba1: 8 hours in total, Prueba2: 9 hours in total
I am stuck trying to dinf they way to sum when 1 or more fields must be the same, I hope someone can help me with this. Thanks!
You must use sum function to add the number of hours for each worker along with GROUP BY clause to group workers.Formatted Query is like:
SELECT SUM(horas) AS Hours,`trabajador`
FROM `horas`
WHERE `proyecto`
LIKE '%".$proyecto."%'
GROUP BY `trabajador`
In your code,
$select = "
SELECT SUM(horas) AS Hours, `trabajador`
FROM `horas`
WHERE `proyecto` LIKE ?
GROUP BY `trabajador`
";
$sth = $conn->prepare($select);
$sth->execute(['%'.$proyecto.'%']);
/* Fetch all of the remaining rows in the result set */
print("Fetch all rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
Note: You better switch to MYSQL prepared statements to keep your data secure and for better database connectivity practices.
Note answer by maniksidana explains how to use SUM() and GROUP BY and is in general valid. However, it mixes mysqli and PDO approches. Here you have sample how to use it with mysqli (as your question uses it) and why it's important to use prepared statements at all. Just add some dummy data to your table end execute it. Personally I'd suggest to go with PDO only instead, but it's matter of taste.
INSERT INTO `horas` (`fecha`, `horas`, `proyecto`, `trabajador`) VALUES
('2020-08-08', 3, 'foo bar baz', 'Joker1'),
('2020-08-09', 4, 'ello pomello', 'Joker2');
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proyecto = "ProyectpDePrueba'; DELETE FROM horas WHERE 1; -- bye bye data";
$proyecto = "ProyectpDePrueba";
$proyecto = "ProyectpDePrueba' OR 1=1 -- no more execution";
// Wrong
$sql = "
SELECT SUM(horas) AS Hours, `trabajador`
FROM `horas`
WHERE `proyecto` LIKE '$proyecto'
GROUP BY `trabajador`
";
$result = $conn->query($sql);
echo '<pre>Wrong' . PHP_EOL;
while ($row = mysqli_fetch_assoc($result)) {
print_r($row);
}
// Correct
$sql = "
SELECT SUM(horas) AS Hours, `trabajador`
FROM `horas`
WHERE `proyecto` LIKE ?
GROUP BY `trabajador`
";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $proyecto);
$stmt->execute();
$result = $stmt->get_result();
echo PHP_EOL . 'Corrcet' . PHP_EOL;
while ($row = $result->fetch_assoc()) {
print_r($row);
}
$conn->close();
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I need a little help again... I get error mysql parameters, I know the problem but I cant find the missing parameters... this is the problem line
**`$result_template = mysqli_query($select_template) or die(mysql_error());`**
I know 1 parameter is missing but I dont know whichone?? Can you pls help me? Thanks
This is part of the codes maybe usefull....
/*function to display the active template*/
function displayTemplate(){
$tableprefix = "";
global $tableprefix,$_SESSION;
$template_array = array();
$select_template = "SELECT vtop_filename,vleft_filename,vbottom_filename,vimages_folder,vcss_name,vtemplate_name
FROM ".$tableprefix."template_master WHERE vactive_status = 'Y'";
1579---->>>> $result_template = mysqli_query($select_template) or die(mysql_error());
$template_row = mysql_fetch_assoc($result_template);
array_push($template_array,$template_row['vtop_filename'],$template_row['vleft_filename'],$template_row['vbottom_filename'],$template_row['vimages_folder'],$template_row['vcss_name'],$template_row['vtemplate_name']);
return $template_array;
}
You need to tell it where to connect to. Here is a simple example of working code to connect to a database from PHP.
<php
//Connect to DB
$conn = new mysqli("Hostname","Username","Password","Database");
//If the connection has errors
if ($conn->connect_error){
//Display the error
die("Connection failed because: " . $conn->connect_error);
}
//Otherwise the connection is good so lets create a sql query
$sql = "SELECT * FROM Database";
//Get the results of the query
$result = $conn->query($sql);
You should refer the php documentation for this here
As you are using the procedural style, so you will have to pass the mysqli_connect resource to your mysqli_query
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* Create table doesn't return a resultset */
if (mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!mysqli_query($link, "SET #a:='this will not work'")) {
printf("Error: %s\n", mysqli_error($link));
}
mysqli_free_result($result);
}
mysqli_close($link);
?>
but as I can see that you are using it in some function so pass an object of db to this function and then use it in your mysqli_query
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.