How to get auto_increment particulars using mysqli_fetch_fields? [duplicate] - php

This question already has an answer here:
how to tell if column is primary key using mysqli?
(1 answer)
Closed 3 years ago.
objectice: to get auto_increment particulars of a field using mysqli_fetch_fields
code:
<?php
require_once("dbc.php");
$query="SELECT id, name, age from student WHERE 1>2";
$result=mysqli_query($dbc, $query);
$metas=mysqli_fetch_fields($result);
foreach($metas as meta){
$col_name=meta->name;
$col_type=meta->type;
$col_length=meta->length;
$col_flags=meta->flags;
echo "col_name: $col_name, col_type: $col_type, col_length: $col_length, col_flags: $col_flags";
}
mysqli_close($dbc);
?>
Observation:
in mysql prompt
mysql> describe student;
Field Type Null Key Default Extra
id int(16) NO PRI NULL auto_increment
but in mysqli
col_name: id, col_type: 3 , col_length: 11, col_flags: 49967
col_flags value 49967 corresponds to primary key.
Please guide me in getting whether a field is auto-increment using mysqli_fetch_fields?

The appropriate flag bit to test for AUTO_INCREMENT is bit 9 (AUTO_INCREMENT_FLAG) (Source). In PHP you just need to add the MYSQLI_ prefix. Something like this:
$auto_increment = $col_flags & MYSQLI_AUTO_INCREMENT_FLAG;

Related

how do I retrieve data which has value 1 as the column name and ignore the data which has value of 0 in php

I'm working on a new project using php and mysql
after inserting the values I want to retrieve them as the column name
I'm using this table
CREATE TABLE categories (
ID INT(8) NOT NULL AUTO INCREMENT
,action INT(1) DEFAULT '0'
,comedy INT(1) DEFAULT '0'
,drama INT(1) DEFAULT '0'
,mystery INT(1) DEFAULT '0'
)
values are either 0 or 1 , I want to retrieve the value 1 as the column name like if action and mystery has value = 1 I want to display them alone
what I'm having a hard time is displaying them as the name and only show value 1
edit as requested some sample data
when I try to get the values they appear 0 or 1
$result = mysqli_query($link,"SELECT * FROM categories WHERE ID = $id");
while ($row = mysqli_fetch_assoc($result)) {
echo '
<div class="categories">
'.$row["action"].' -
'.$row["comedy"].' -
'.$row["drama"].' -
'.$row["mystery"].' </div>'
what I want is the 1 to be named as the column name
You can iterate over array keys of first row to get column names. But better option is to use ORM schemes and get titles from there.
One solution (but not recomennded, because you must iterate over all columns you retrieve from table). And you show also ID column name.
echo '<div class="categories">' . implode(array_keys($row), ' - ') . '</div>';
Second thing is that your design of database is very bad. I don't know exact purpose but you should have for categories only two columns: ID and name.
after looking for the optimal table thanks to kerbh0lz and tajniak I found it
create table statement
create table categories (categoryid int(1), category varchar(20) );
inserting new genres
insert into categories values
(1 ,'action'),
(2 ,'comedy'),
(3 ,'drama'),
(4 ,'mystery');

How to properly retrieve unsigned bigint from MySQL column with PHP? [duplicate]

This question already has answers here:
Display binary(16) column as hex in mysql
(4 answers)
PHP mysql bigint issue
(3 answers)
Closed 2 years ago.
I'm not sure if it's PHP or MySQL that's messing me up.
Say, I have a table with BIGINT UNSIGNED column (let's name it flgs). I read data from that table with PHP as such:
$query = "SELECT * FROM `$tbl_nm` ORDER BY `$colID` ASC";
$res = mysqli_query($link, $query);
if($res)
{
while($aRow = mysqli_fetch_assoc($res))
{
echo("flags=0x".dechex($aRow['flgs'])."<br>");
}
}
if the flgs column has value with bit-63 reset, then I get the correct result. But if bit-63 is set, the return value is 0x7fffffffffffffff. Hmmmm?
For instance, if flgs is set to 0x8000000000000000 in the database, my code above prints:
flags=0x7fffffffffffffff
Why, PHP, why?

How to create username unique with respect to database? [duplicate]

This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 2 years ago.
I have one field named
username:_________
now i want to add manuaaly username to the database
if once added and i add same next time it must automatically show invalid username right side of textbox i am searching same code on net and tried too many solution but not working.
This i want to performed in php and mysqli
Just mark it as UNIQUE.
CREATE TABLE User
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
And in PHP script do something like this:
$query = mysqli_query($con, "SELECT id FROM user WHERE username='$username'");
if(mysqli_num_rows($query) > 0){
echo "Username already exists";
}else{
// do something
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
}
And if you want to check in realtime if username is available (like #Arun pointed) maybe this would help a bit.

How can I change this code to INSERT instead of UPDATE if content doesn't exist? [duplicate]

This question already has answers here:
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
(12 answers)
Closed 8 years ago.
I have a query that will update a row in the database, which works fine providing there is a row there to begin with.
How could I say; update if exists insert if doesn't?
require_once('../scripts/includePDO.php');
$who = $_SESSION['who'];
$formText = $_POST['protext'];
$sql = "UPDATE tbl_profiles SET proText = :formText WHERE user_id = :who";
$q = $conn->prepare($sql);
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->bindValue(':formText',$formText,PDO::PARAM_STR);
$q->execute();
header("Location: ../settings/?status=Done");
Assuming user_id is a unique key in the db:
$sql = "INSERT INTO tbl_profiles (user_id, proText) VALUES (:who, :formText) ON DUPLICATE KEY UPDATE proText = :formText";
Your SQL query should be:
INSERT INTO tbl_profiles (user_id,proText) VALUES (:who,:formText)
ON DUPLICATE KEY UPDATE proText=:formText
This is assuming that user_ID is a unique id
1- simple way is use ORM such as Dotrine
2- How ORM handle this :
usually tables has primary key(id) that should not be null .if you have update then you had select that load this data . in you select load id field in you data structure (array or object or something else) . in save method only check current row you want save that it has id (if this record has id then it exist and need to update else you should save).

Autoincrement Primary Key in MySQL when data received from form [duplicate]

This question already has an answer here:
Mysql - Add auto_increment to primary key
(1 answer)
Closed 9 years ago.
I have a form that sends the data it captures in to a database, i have a primary key attached to my table (form_id) which i want to autoincrement everytime a new form is submitted and consequently added into my database table. Currently it is just adding a 0 for the first form submitted then anymore forms i submit after do not show as it gives me a message saying you can not have two rows with the same id as zero, which is correct so i would like to change this?
Below is my php code that submits the data into the database:
public function action_claimincentive() {
$this->template->content = View::factory('crm/uk/claim_incentive_form');
$this->template->content->thanks = false;
$this->template->content->val = '';
$this->template->content->post = '';
if ($this->request->post('form')) {
$post = $this->request->post('form');
$stmt = DB::query(Database::INSERT, 'INSERT INTO `claim_incentive_form_data` (`Claimant Name`, `Claimant Postcode`, `Purchase Order No.`, `Claimant Email Address`, `Storename`, `Storetown`, `Date of Sale`, `Date of Delivery`, `Tempur Acknowledgement No.`, `Tempur Product`)
VALUES (:claimantname, :claimantpostcode, :orderno, :email, :storename, :storetown, :dateofsale, :dateofdelivery, :acknowledgementno, :tempurproduct)');
$stmt->param(':claimantname', $post['claimantname']);
$stmt->param(':claimantpostcode', $post['claimantpostcode']);
$stmt->param(':orderno', $post['orderno']);
$stmt->param(':email', $post['email']);
$stmt->param(':storename', $post['storename']);
$stmt->param(':storetown', $post['storetown']);
$stmt->param(':dateofsale', $post['dateofsale']);
$stmt->param(':dateofdelivery', $post['dateofdelivery']);
$stmt->param(':acknowledgementno', $post['acknowledgementno']);
$stmt->param(':tempurproduct', $post['tempurproduct']);
try {
$stmt->execute();
$this->template->content->post = $post;
$this->template->content->thanks = true;
} catch (Exception $e) {
FB::error($e);
}
}
}
This sounds more like a MySQL issue rather than anything else. Make sure you have your Primary Key setup to auto increment. Try altering the table to add the auto increment feature:
ALTER TABLE [table name] MODIFY COLUMN [column name] [column type] PRIMARY KEY AUTO_INCREMENT;
In the above example. Replace the keys in brackets with their appropriate names. Replace [table name] with the name of your table, [column name] with the name of the column and [column type] with the type of the column (SMALLINT, INT, etc).
For more information, see this answer posted by roman.
For more information on the AUTO_INCREMENT feature, check out the MySQL Development Documentation here.
You need to add AUTO_INCREMENT to the primary key column on the table check this http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
you should be able to alter the table with something like this
ALTER TABLE claim_incentive_form_data CHANGE id id INT(10)AUTO_INCREMENT PRIMARY KEY;
Just make sure you change the id column and the datatype if yours are diffrent from that.
You have to set the auto_increment setting in the table within mysql.
ALTER TABLE `claim_incentive_form_data` MODIFY COLUMN `your_primary_column` int(4) PRIMARY KEY AUTO_INCREMENT
Refs:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
http://dev.mysql.com/doc/refman/5.0/en/alter-table.html
you have to set form_id as primary key, auto increment and not null.

Categories