php mysql insert (max(id)+1) - php

I have a table image_tb, which has 3 fields, id,images,link (id is auto auto_increment), this is my insert code:
mysql_query("
insert into image_tb
(images,link)
select
'".(max(id)+1).".jpeg','".$link."'
from image_tb
");
it return:
Warning: max(): When only one parameter is given, it must be an array
how to modify? thanks.

its better you define a function , get the last id by query like this:
"select id from image_tb order by id desc limit 0,1"
then increase it , its realibe .

I think you don't mean to close the string:
select '" ...
should be
select MAX(id) + 1
Otherwise you are using the php function max, and I don't think you intend to do that at all.
By the way, you shouldn't be using mysql_*. Use PDO or mysqli.

do it inside the query,
mysql_query("
insert into image_tb (images,link)
select CONCAT(COALESCE((SELECT MAX(ID) + 1 FROM image_tb),1), '.jpeg'),'".$link."'
from image_tb
");
your query is vulnerable with SQL Injection, please read the article below to protect from it
How can I prevent SQL injection in PHP?

Have you considered something like this?
Insert data with empty filename
Update table where filename is empty, set filename to CONCAT(id, ".jpeg") or something (CONCAT is function used to "add" strings).

Related

Error trying to select field while not selecting first character

I'm getting the error: Incorrect syntax near the keyword 'AS'.
I'm trying to select a column from my MSSQL database while NOT SELECTING the first character of that field.
Below is the code (Within PHP):
$sql = "SELECT RIGHT(Column, LEN(Column) - 1) FROM Table WHERE [Column] ='".$search."' AS Column2";
First of all. Please be careful. Your code looks vulnerable to an SQL injection. Better use paramterized queries.
The second "AS" at the end is not needed.
Try it that way:
SELECT RIGHT(Revlv, LEN(Revlv) - 1) AS Revlv2 FROM table_name WHERE [Objkt] ='".$search."'
Or better yet:
SELECT RIGHT(Revlv, LEN(Revlv) - 1) AS column_name FROM table_name WHERE [Objkt] = ?
Read more about parameterized queries here
Also take care when the Revlv column only contains an empty string. The query will fail in that case.
try this:
$sql = "SELECT RIGHT(Column, LEN(Column) - 1) AS Column2 FROM Table WHERE [Column] ='".$search."' ";
As all answers simply fix the syntax instead of fixing the logic:
There's no need to use RIGHT + LEN to extract everything but the first character, simply use
substring(Revlv from 2) AS Revlv2 -- Standard SQL to extract everything after the first character
As SQL Server has a slighty different syntax:
substring(Revlv, 2, 8000) AS Revlv2 -- T-SQL to extract everything after the first character
You need to put AS after the SELECT part of your query never put it at the end of your query. Try to do it like this
$sql = "SELECT RIGHT(Column, LEN(Column) - 1) AS Column2 FROM Table WHERE [Column] ='".$search."' ";
SOURCE
try this.
$sql="SELECT RIGHT(Revlv, LEN(Revlv)-1) AS Revlv2
FROM tablename where['objkt']='$search'";

PHP & MySQL SELECT Substring

$content is a variable with a 'detailed description'.
product_id is column which might contain a substring of the detailed description ($content) in a MySQL table called products
I am trying to create a select statement that would find a record if the product_id is CONTAINED in the $content variable. Then I want to update another table called receive_sms with the url field from the SELECT staement
Researching on the website I have come up with the following.... But it doesn't work
$mysqlic = mysqli_connect("testsms.cloudaccess.net", "username", "password", "testsms2");
$prod_res=mysqli_query($mysqlic,"SELECT url from products
WHERE %product_id% LIKE %$content%");
mysqli_query($mysqlic,"INSERT INTO recieve_sms (comments) VALUES ('$prod_res')");
Any Ideas??
It should be:
$prod_res = mysqli_query($mysqlic, "SELECT url from products
WHERE '$content' LIKE CONCAT('%', product_id, '%')");
or:
$prod_res = mysqli_query($mysqlic, "SELECT url from products
WHERE LOCATE(product_id, '$content') != 0");
You need to put $content in quotes.
Actually, it would be better if you used a prepared query, then '$content' would become a placeholder ?.
After you query, you need to call mysqli_fetch_assoc() to get the column value:
$row = mysqli_fetch_assoc($prod_res);
$url = $row['url'];
Well, first of all, I don't understand why you're using wildcards on you field name. You want to check if a value is contained within the value of that field, consider changing this:
... WHERE %product_id% LIKE %$content%);
to
... WHERE product_id LIKE '%$content%');
Also, please, use prepared statements to avoid SQL injection. You're using MySQLi, which supports them.
EDIT
Also, the return of a mysqli_query is a MySQLi Resource. You'll have to fetch the results from the resource to gain access to the value you're looking for.

SQL: last id from a table selecting database

I have the following query in my php script:
SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'MYTABLE' AND last_value IS NOT NULL
This works great, it returns the last id from MYTABLE which is what I need.
But, as I'm going to have more than one database I should modify the query to select the database where MYTABLE is.
I'm doing:
SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'mydatabase.dbo.MYTABLE' AND last_value IS NOT NULL
But this does not work, I get nothing in return.
Any ideas?
Thanks a lot!
When you execute an SQL statement, it runs in the context of a database you specified on connection. In order to query a different database you should change the database context.
Try this:
USE MyDatabase;
SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'MYTABLE' AND last_value IS NOT NULL
If you need to pass the database name as a variable IDENT_CURRENT accepts a database qualified object name. e.g.:
SELECT IDENT_CURRENT('mydatabase.dbo.MYTABLE');
As an unrelated aside it would be better to use:
WHERE OBJECT_ID = OBJECT_ID(N'MYTABLE');
Instead of
WHERE OBJECT_NAME(OBJECT_ID) = 'MYTABLE'
Since if MYTABLE was not in the default schema, it would fail, consider a table MYSCHEMA.MYTABLE. This returns no rows
WHERE OBJECT_NAME(OBJECT_ID) = 'MYSCHEMA.MYTABLE'
Whereas this would:
WHERE OBJECT_ID = OBJECT_ID(N'MYSCHEMA.MYTABLE');

Check for duplication before insertion

Problem
I have a table tbl_student_courses which join 2 tables student and courses now when data is inserted it is the combination of 2 ids course_id and student_id. I just want there would be no duplication of this combination in tbl_student_courses.
Code
foreach($_POST['sel_course'] as $val) {
$query_std_course = "
INSERT INTO
`tbl_student_courses`
SET
`course_id` = '".$val."',
`std_id` = '".$_POST['std']."',
WHERE NOT EXISTS (
SELECT * FROM `tbl_student_courses` WHERE course_id=$val AND std_id=$std
)";
}
Help
This query giving SQL syntax error.
Can any body help me?
Thanks in advance.
Probably you are missing quotes one inner query values.
You SQL query should look like this
$sql = "
INSERT INTO
`tbl_student_courses`
SET
`course_id` = '".$val."',
`std_id` = '".$_POST['std']."',
WHERE NOT EXISTS (
SELECT * FROM `tbl_student_courses` WHERE course_id='".$val."' AND std_id='".$std."'
)";
NOTE: Inserting in database not prepared statements like std_id = '".$_POST['std']."' is not of a good manner. Consider using PDO or filter data yourself, bec. this can be easily used for SQL Iinjection therefore it is potential security breach.
UPDATE: Try to use ON DUPLICATE KEY UPDATE or INSERT IGNORE INTO table.
You can find more information regarding your implementation - http://bogdan.org.ua/2007/10/18/mysql-insert-if-not-exists-syntax.html
And read about proposed implementation - http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html
The SQL syntax you seek is the MERGE statement, or its equivalent on your platform
http://en.wikipedia.org/wiki/Merge_(SQL)

MySQL IN CLAUSE duplicates WANTED

$sql = 'SELECT * FROM `courses` WHERE `id` IN ('. implode(",", $course[0]) .')';
This is the code I just had help with, I have used it before but the problem with it is, when something for example 1,1,2,3 is passed into the IN clause I will not get all values returned.
1x1
2x1
3x1
I want
1x2
2x1
3x1
All values must be returned otherwise it will mess up my table, any suggestions?
You won't be able to do that in SQL. Query by id and then use whatever language your are using to to do the 'multiplication'.

Categories