I know this isn't so complicated but I can't remember how to do.
I just need to know the next auto increment.
$result = mysql_query("
SHOW TABLE STATUS LIKE Media
");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
...but i won't work for me, what am I doing wrong?
$result = mysql_query("
SHOW TABLE STATUS LIKE 'Media'
");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
The name of the table needed to be wrapped with single quotes like this: 'table_name'
So it works just fine now.
:)
The query should look like this:
SHOW TABLE STATUS WHERE `Name` = 'Media';
Another way, but slow, is:
SELECT AUTO_INCREMENT FROM information_schema.`TABLES` T where TABLE_SCHEMA = 'myScheme' and TABLE_NAME = 'Media';
The information_schema is mostly usefull for getting data from many schemes.
You can also use this function
function getNextValue(){
$query = "SHOW TABLE STATUS LIKE 'vendors'";
dbconnect();
$results=mysql_query($query);
if(mysql_errno() != 0) {
$result['count'] = -1;
$result['error'] = "Error: ".mysql_error();
} else {
$result['count'] = mysql_num_rows($results);
for($counter=0;$counter<$result['count'];$counter++) {
$result[$counter] = mysql_fetch_assoc($results);
}
}
return $result[0]['Auto_increment'];
mysql_close();
}
SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "database_name"
AND TABLE_NAME = "table_name";
if you need to know the next auto_increment, then it's 99% likely you're doing it wrong. instead of the getting the next auto_increment, you should just do the insert you're about to do, then use SELECT LAST_INSERT_ID() to get the auto_increment value from that insert.
if you try to guess the next auto_increment value and you have multiple users doing it at the same time, you'll frequently get the wrong value.
Related
I am working on an Android app that connects to an sql database through php files. Currently I am having problems with the like function on one of my queues.
Here is the code of the file where the problem is:
$con = mysqli_connect($host,$uname,$pwd,$db) or die("connection failed");
$like = $_REQUEST['like'];
$sql_q = mysqli_query($con,"SELECT `ID`, `Value`, `Value_Complete` FROM `products` WHERE `ID` LIKE '$like'");
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
}
if($output)
{
print(json_encode($output));
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "\n";
}
mysqli_close($con);
?>
This code works with this query - SELECT ID, Value, Value_Complete FROM products WHERE ID LIKE '11/02/__/00/%' - and returns:
[{"ID":"11\/02\/00\/00\/00\/0\/0\/0","Value":"Tradicionais","Value_Complete":""},
{"ID":"11\/02\/01\/00\/00\/0\/0\/0","Value":"Caipis","Value_Complete":""},
{"ID":"11\/02\/02\/00\/00\/1\/0\/0","Value":"Daiquiri","Value_Complete":""},
{"ID":"11\/02\/03\/00\/00\/1\/0\/0","Value":"Gin Tonico","Value_Complete":""},
{"ID":"11\/02\/04\/00\/00\/1\/0\/0","Value":"Long Island Ice Tea","Value_Complete":""},
{"ID":"11\/02\/05\/00\/00\/1\/0\/0","Value":"Manhattan","Value_Complete":""},
{"ID":"11\/02\/06\/00\/00\/1\/0\/0","Value":"Margarita","Value_Complete":""},
{"ID":"11\/02\/07\/00\/00\/1\/0\/0","Value":"Martini Seco","Value_Complete":""},
{"ID":"11\/02\/08\/00\/00\/1\/0\/0","Value":"Black Russian","Value_Complete":""},
{"ID":"11\/02\/09\/00\/00\/1\/0\/0","Value":"White Russian","Value_Complete":""},
{"ID":"11\/02\/10\/00\/00\/1\/0\/0","Value":"Sex on the Beach","Value_Complete":""},
{"ID":"11\/02\/11\/00\/00\/1\/0\/0","Value":"Sidecar","Value_Complete":""},
{"ID":"11\/02\/12\/00\/00\/1\/0\/0","Value":"Sakerinha","Value_Complete":""},
{"ID":"11\/02\/13\/00\/00\/1\/0\/0","Value":"Tequila Sunrise","Value_Complete":""},
{"ID":"11\/02\/14\/00\/00\/0\/0\/0","Value":"Vodka","Value_Complete":""}]
The same query returns this in phpMyAdmin:
However, the same code does not work with the query - SELECT ID, Value, Value_Complete FROM products WHERE ID LIKE '$like'. It returns an empty result set but in phpMyAdmin returns:
I just can't figure out the issue here... Even this - SELECT ID, Value, Value_Complete FROM products WHERE ID LIKE '%'- returns nothing, when it should return everything.
Could you help me? Thanks.
try to change your query:
$con = mysqli_connect($host,$uname,$pwd,$db) or die("connection failed");
$like = $_REQUEST['like'];
$sql_q = mysqli_query($con,"SELECT `ID`, `Value`, `Value_Complete` FROM `products` WHERE `ID` LIKE '%".$like."%'");
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
}
if($output)
{
print(json_encode($output));
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "\n";
}
mysqli_close($con);
?>
Basically like in something work as equal to (=) but it give you the flexibility to use wild card. % wild card use to define in sql query that there is something but not matter.
If you are not use % with your query it means you are searching same string that is stored in $like variable.
In phpmyadmin you don't need to use %. Because phpmyadmin is designed to the make the use of database easy. So when you select like in search option it automatically add % before applying query on database.
Due to this reason you see these difference.
Add % to the variable
"SELECT `ID`, `Value`, `Value_Complete` FROM `products` WHERE `ID` LIKE '$like%'"
Please try this this complete solution according to your requirements
SELECT tablename FROM id WHERE FIND_IN_SET('/',$column name);
It uses the find_in_Set mysql function which takes 2 parameters, one is the separator and the other is the column name.
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
I am trying to add a column by checking if it exists. If not it should give message that it already exists with the code below.
$prefix = 'vm_';
$col_name = 'checking';
$col = "SELECT ".$col_name." FROM ".$prefix."users";
if (!$col){
$insert_col = "ALTER TABLE ".$table." ADD ".$col_name." DATETIME NOT NULL";
mysql_query($insert_col);
echo $col_name.' has been added to the database';
} else {
echo $col_name.' is already exists';
}
But it doesn't add any column and directly displays message that the column already exists.
You never execute your query, your condition is instead your query string:
if (!$col) { //always false, since a nonempty string is always truthy
Here is the final code. There was stupid mistake; I didn't use mysql_query for $col
$prefix = 'vm_';
$col_name = 'checking';
$col = mysql_query("SELECT ".$col_name." FROM ".$prefix."users");
if (!$col){
//$insert_col = "ALTER TABLE ".$table." ADD ".$col_name." DATETIME NOT NULL";
mysql_query("ALTER TABLE ".$prefix."users ADD ".$col_name." DATETIME NOT NULL");
echo $col_name.' has been added to the database';
} else {
echo $col_name.' is already exists';
}
You have to run your query before you check statements with it. It's like you can't see whether the box is empty of not (i.e. result of your query) without opening the box (i.e. running the query)
Replace your line 04 with this
$col = mysql_query("SELECT ".$col_name." FROM ".$prefix."users");
Then your problem will be solved
For more information on mysqli, please read this article
You might consider moving on to PDO statements as well.
Hope this helps
You haven't executed your query. First execute your query, then check the condition on it.
This is what I did and it works:
$db= new mysqli('host','user','password','db');
$query = "SHOW COLUMNS FROM tablename LIKE 'columnname'";
$db->query($query);
if(empty(empty($db->num_rows)) {
$alter = "ALTER TABLE tablename ADD columnname varchar(50) NOT NULL";
$db->query($alter);
} else {
echo 'column exists';
}
I have a feeling that my syntax is incorrect but I can't narrow down what's going on. I have no issues running the statement in a phpMyAdmin SQL query, so hopefully I can get pointed in the right direction. My code is as follows:
else if ($resultdetails === 1) {
$query3 = "update customer_det set `10k`='$_10k',
`14k`='$_14k', `18k`='$_18k', `21k`='$_21k', `22k`='$_22k',
`24k`='$_24k', `925k`='$_925k', `coins`='$coins', `bars`='$bars'
where `id` = '".$uid."'";
$result3 = mysql_query($query3);
}
$resultdetails is a variable set with a EXISTS function. In the SQL query, it returns 1 for me, because the row I'm looking for does exist. So there should be no issues with that.
I tried the double ==, as well as the triple, and there doesn't seem to be any difference in results. I believe the triple === means that it's identical, i.e. the datatype is the same and the value is the same.
I think the issue here is the WHERE statement. Any ideas or suggestions would be greatly appreciated. I forgot to mention that customer_det is the table to be updated and id is the primary key, autoincremented. I pull the $uid variable from the database as well.
Your sql query is right !
But your else if is the problem !
see you add ===,
change it with == and i'm also doubt with your variable declare,
your code will look
like this:
else if ($resultdetails == 1) {
$query3 = "update customer_det set `10k`='".$_10k."',
`14k`='".$_14k."', `18k`='".$_18k."',
`21k`='".$_21k."', `22k`='".$_22k."', `24k`='".$_24k."', `925k`='".$_925k."', `coins`='".$coins."', `bars`='".$bars."' where `id` = '".$uid."'";
$result3 = mysql_query($query3);
}
EDIT:
if (CONDITION :: IF FOUND ON DATABASE) {
$query3 = "update customer_det set `10k`='".$_10k."',
`14k`='".$_14k."', `18k`='".$_18k."',
`21k`='".$_21k."', `22k`='".$_22k."', `24k`='".$_24k."', `925k`='".$_925k."', `coins`='".$coins."', `bars`='".$bars."' where `id` = '".$uid."'";
$result3 = mysql_query($query3);
} else {
// Insert query if not found
}
Check for the data type for $uid and $_blahblah
Try this query --
else if ($resultdetails == 1) {
$query3 = "update customer_det set `10k`='$_10k',
`14k`='$_14k', `18k`='$_18k', `21k`='$_21k', `22k`='$_22k',
`24k`='$_24k', `925k`='$_925k', `coins`='$coins', `bars`='$bars'
where `id` = $uid";
$result3 = mysql_query($query3);
}
What is the best way to check if a table exists in MySQL (preferably via PDO in PHP) without throwing an exception. I do not feel like parsing the results of "SHOW TABLES LIKE" et cetera. There must be some sort of boolean query?
Querying the information_schema database using prepared statement looks like the most reliable and secure solution.
$sql = "SELECT 1 FROM information_schema.tables
WHERE table_schema = database() AND table_name = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$tableName]);
$exists = (bool)$stmt->fetchColumn();
If you're using MySQL 5.0 and later, you could try:
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = '[database name]'
AND table_name = '[table name]';
Any results indicate the table exists.
From: http://www.electrictoolbox.com/check-if-mysql-table-exists/
Using mysqli I've created following function. Assuming you have an mysqli instance called $con.
function table_exist($con, $table){
$table = $con->real_escape_string($table);
$sql = "show tables like '".$table."'";
$res = $con->query($sql);
return ($res->num_rows > 0);
}
Hope it helps.
Warning: as sugested by #jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $table var is clean or even better use parameterised queries.
This is posted simply if anyone comes looking for this question. Even though its been answered a bit. Some of the replies make it more complex than it needed to be.
For mysql* I used :
if (mysqli_num_rows(
mysqli_query(
$con,"SHOW TABLES LIKE '" . $table . "'")
) > 0
or die ("No table set")
){
In PDO I used:
if ($con->query(
"SHOW TABLES LIKE '" . $table . "'"
)->rowCount() > 0
or die("No table set")
){
With this I just push the else condition into or. And for my needs I only simply need die. Though you can set or to other things. Some might prefer the if/ else if/else. Which is then to remove or and then supply if/else if/else.
Here is the my solution that I prefer when using stored procedures. Custom mysql function for check the table exists in current database.
delimiter $$
CREATE FUNCTION TABLE_EXISTS(_table_name VARCHAR(45))
RETURNS BOOLEAN
DETERMINISTIC READS SQL DATA
BEGIN
DECLARE _exists TINYINT(1) DEFAULT 0;
SELECT COUNT(*) INTO _exists
FROM information_schema.tables
WHERE table_schema = DATABASE()
AND table_name = _table_name;
RETURN _exists;
END$$
SELECT TABLE_EXISTS('you_table_name') as _exists
As a "Show tables" might be slow on larger databases, I recommend using "DESCRIBE " and check if you get true/false as a result
$tableExists = mysqli_query("DESCRIBE `myTable`");
$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
foreach( $row as $key => $value )
{
if ( $value = BTABLE ) // BTABLE IS A DEFINED NAME OF TABLE
echo "exist";
else
echo "not exist";
}
}
Zend framework
public function verifyTablesExists($tablesName)
{
$db = $this->getDefaultAdapter();
$config_db = $db->getConfig();
$sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}' AND table_name = '{$tablesName}'";
$result = $db->fetchRow($sql);
return $result;
}
If the reason for wanting to do this is is conditional table creation, then 'CREATE TABLE IF NOT EXISTS' seems ideal for the job. Until I discovered this, I used the 'DESCRIBE' method above. More info here: MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050
Why you make it so hard to understand?
function table_exist($table){
$pTableExist = mysql_query("show tables like '".$table."'");
if ($rTableExist = mysql_fetch_array($pTableExist)) {
return "Yes";
}else{
return "No";
}
}