Redefine Row Name - php

Is it possible to redefine a rows name when I use SELECT in MySQL?
"SELECT posts.id AS the_post_id FROM posts"
So I can call it from PHP as:
$query = mysql_query("SELECT posts.id AS the_post_id FROM posts");
while($row = mysql_fetch_array($query)){
// I call the ID with `the_post_id` and not `id`
echo $row["the_post_id"];
}

Yes, you have already done it correctly. Are you having issues with that?
Edit:
$query = mysql_query("SELECT posts.id AS the_post_id FROM posts") or die(mysql_error());
Try it like that and it would tell you if there is any issue with the query itself. Also i would suggest you look at the newer mysqli_* functions, mysql_* functions are history.

Related

Why is ORDER BY id DESC not working in this line?

I'm trying to get ORDER BY id DESC to work in this line of php but I can't get it to work. It works without it though but they just display in the opposite order. Where should I position it?
$query = mysql_query("SELECT * FROM photos ORDER BY id DESC WHERE title LIKE '%".$search."%'");
Update:
I've updated the php with your suggestion that works now thanks. I've also updated it to mysqli as suggested, could this be structured better in anyway? It is working, just wondered if anyone has any improvements?
<?php
$search = $_GET['search'];
$db = mysqli_connect("", "", "", "") or die ("could not connect to mysql");
$sql = "SELECT * FROM photos WHERE title LIKE '%".$search."%' ORDER BY id DESC";
$result = mysqli_query($db, $sql);
if(mysqli_num_rows($result) >=1) {
while ($row = mysqli_fetch_array($result)) {
echo"<div id='img_div'>";
echo"<img src='images/".$row['image']."'>";
echo"<h1>".$row['title']."</h1>";
echo"<p>".$date = date('j F, Y', strtotime($row['date']))."</p>";
echo"<p>".$row['link']."</p>";
echo"</div>";
}
//continue
}else{
echo "No Results";
}
?>
Your query is wrong. ORDER BY id DESC should be placed after the WHERE clause, like this:
$query = mysql_query("SELECT * FROM photos WHERE title LIKE '%".$search."%' ORDER BY id DESC");
Sidenote(s):
Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
Learn about prepared statement because right now your query is susceptible to SQL injection attacks. Here's a good read on how you can prevent SQL injection in PHP.

PHP MySQL query result into a variable and then echo ($variable)

wish to check the last id (cat_id) in a table (category) and insert that result into a variable that I can echo.
My intention is to create a record last cat_id +1 as long as it doesnt already exist of course.
What I thought I should do was something like this;
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
echo ($result);
?>
But oh no, nothing so simple. The echo was only to check I had the correct result (in phpmyadmin it returns the desired number)
Then I was hoping to be able to, with a simple html form, was to ask if the user wanted to add a category through a text box:
addrec.html:
<form action="addrec.php" method="post">
Category: <input type="text" name="category">
<input type="submit">
</form>
addrec.php:
<?php
require "mydbdetails.php";
$new_id = $result + 1;
$query="INSERT INTO category VALUES ($new_id, 'Fruits')";
?>
You must first know as a developer, that mysql extension in php will be fully deprecated in the future as it is already in the newer php versions. So use instead Mysqli extension and PDO for sanitation and securer code for your database.
As it goes to your question:- Try the following ;
// Make a MySQL Connection
$query = "SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
//assign result to a variable
$result = mysql_query($query) or die(mysql_error());
//fetch result as an associative array
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['cat_id'];
You can assign it to avariable $row['cat_id'] = $catId; like that and use it .
echo $result[0]['cat_id'] i think
Please consider using PDO query Syntax instead of the old deprecated mysql_query.
If you make a PDO connection and store it in the $conn object ( pretty similar to what you already have in mydbdetails.php) just do:
$query=$conn->query("SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1");
$result=$query->fetchAll(PDO::FETCH_COLUMN,0);
echo ($result[0]);
First of all, you should really be using mysqli instead of mysql because mysql is deprecated and will be removed in PHP 5.5.
Of course the PDO would be better, but i think that you're so new that it would be a bit to much right now.
Basically, you're firing a Query, but you don't tell the query to what connection. You're doing this:
$result=mysql_query($query);
What it should be is
$result=mysqli_query($link, $query);
Where $link is the variable where you're setting up the database connection in the mydbdetails.php file.
Without the connection the Query doesn't know where to get the data from.
But if OOP isn't new to you, the answer from #amenadiel is better because it's an OOP way.
Further, there is no need for your $new_id = $result + 1; line.
IDs should almost always set to Auto Increament in the database, so this line will be done automatically in the database when you're adding a new dataset.
More information here
Hope this helps
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
$i;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
var_dump($row); /* dump rows*/
/* or add to array to use later */
$results[$i] = $row; // add to array
$i++; // +1 the counter to increment the array
}
?>
Try to write your scripts in mysqli_ or pdo functions. Work around in mysql_ function (not recommended)
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$cat_id = $row['cat_id'] + 1;
} else {
$cat_id = 1;
}
?>
cat_is is the primary key? If yes you can set that column as auto increment. You can try this
https://php.net/manual/en/function.mysql-result.php

How to display field from MySQL?

I'm trying to display a field from my MySQL database. It's in the table tblproducts in the row with the id is set to 1. And under the column qty.
This is the code I'm using:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database_name");
$available = "SELECT qty FROM tblproducts WHERE id = 1";
$result = mysql_query($available);
echo $result;
?>
However, I keep getting this message: Resource id #2
I've done a bit of research and seen where other people are having similar problems but most of them are trying to display their data in an HTML table whereas I just need the data from 'qty' to display. And of course I'm definitely not a MySQL guru.
Can anyone help me out with this please?
Try changing this:
$result = mysql_query($available);
To this:
$result = mysql_result(mysql_query($available), 0);
Let's start from the start. (I'll assume you have the connection set)
Form the query
$query = "SELECT `qty`
FROM `tblproducts`
WHERE `id` = 1";
Execute the query
$run = mysql_query($query);
Now, put the result in an assoc array
$r = mysql_fetch_array($run);
See the contents of the array
echo $r['qty'];
It's also advised that you move up from mysql to either mysqli, or PDO. PDO is preferred as you're not bound to the MySQL database model.
Try this:
Here you need to generate associative array and then get the resulting row.
$query = "SELECT `qty` FROM `tblproducts` WHERE `id` = 1";
$run = mysql_query($query);
$r = mysql_fetch_array($run);
echo $r['qty'];
-
Thanks

PHP mysql_query where x = $this or $that

I currently have a mysql_query line that looks like this:
mysql_query("SELECT * from users WHERE id = '". $id1 ."' ") or die(mysql_error());
However, I want to select everything from users where id = $id1 OR $id2. How would I edit this line to do so?
I've thought about just having two copies of this line, one with $id1 and one with $id2. However, I'm sure that there is a more efficent way to accomplish this. I'm very new to SQL.
The answer is almost in your question. You should change the query into this:
mysql_query("SELECT * from users WHERE id = '". $id1 ."' OR id = '" . $id2. "'")
You should however not be using the mysql_* functions anymore, since they are deprecated. Use mysqli_* or PDO instead.
You can use the IN clause just like the example below.
SELECT * FROM employees WHERE id IN ( 250, 220, 170 );
Your query statement can be something like
$query = "SELECT * FROM users WHERE id IN('{$id1}','{$id2}')";
or,
$query = "SELECT * FROM usrs WHERE id = '{$id1}' or id = '{$id2}'";
mysql_* is officially deprecated, so use mysqli or PDO to query your statements.

How to display table data in reverse? (php)

I have simple code for displaying images. I created table with 4 columns (ID, location, capture, equence) and inserted there 18 records. My question is: how to display all records from table in reverse mode? I need to make that the last entry will be displayed first, and the first entry displayed last.
What I need: 18-1
What I have now: 1-18
I was searching for simple codes to do that, but notwing worked at all. So i'd be very grateful if someone will help me to solve that problem.
Heres the basic code of my display script:
<?php
mysql_connect("localhost", "***", "***") or die(mysql_error());
mysql_select_db("martinidb1337") or die(mysql_error());
$result = mysql_query("SELECT * FROM klpgalerija") or die(mysql_error()); while($row = mysql_fetch_array( $result )) {
echo '<p><img src="'.$row['location'].'"></p>';
}
You have to use MySQL ORDER BY clause for that,
SELECT * FROM klpgalerija ORDER BY id DESC
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated.
So use either PDO or MySQLi (IMO PDO is way to go)
Changed query from "SELECT * FROM klpgalerija" to "SELECT * FROM klpgalerija ORDER BY ID DESC"
<?php
mysql_connect("localhost", "***", "***") or die(mysql_error());
mysql_select_db("martinidb1337") or die(mysql_error());
$result = mysql_query("SELECT * FROM klpgalerija ORDER BY ID DESC") or die(mysql_error()); while($row = mysql_fetch_array( $result )) {
echo '<p><img src="'.$row['location'].'"></p>';
}
add an order by desc clause in your sql query
$result = mysql_query("SELECT klpgalerija.* FROM klpgalerija order by klpgalerija.ID desc") or die(mysql_error());

Categories