mysqli and field types - php

I'd like to know if there is a simple way to fetch data from mysql tables with "correct" data types? What i mean, if field type is for example INT or SMALLINT is it possible to pass those types directly to PHP as integers?
I did some searching and found mysqli_fetch_fields, but for SMALLIT type is 2, for INT 3 and so on. It could be done that way, but it looks rather clumsy workaround. Is there any better way?
I'm using PHP and mysqli.
Thank you.

The most straightforward way is to build your own database handler on top of the mysqli calls that does that for you.

http://www.php.net/manual/en/mysqli-result.fetch-field-direct.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for column 'SurfaceArea' */
$finfo = $result->fetch_field_direct(1);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
$result->close();
}
/* close connection */
$mysqli->close();
?>

You can use this code
SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'yourtablename replace your table name' AND COLUMN_NAME = 'tablecolumnname replace your table column name';
Use this before run your main query and after when you get your datatype then execute your operation.

Related

count number of rows in table using php

I just want to count the number of rows in a table that already created in a database using php. I used mysqli(). I need the number of rows in the table as the output.
<?php
$mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT count(*) cc FROM tablename")) {
/* fetch the first row as result */
$row = $result->fetch_assoc();
printf("Result set has %d rows.\n", $row['cc']);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
In fact it's a common question you can find the answer anywhere.
Like, http://php.net/manual/en/mysqli-result.num-rows.php
You could separate this problem in to two
I wanna know how to connect to mysql.
I wanna know how to write that sql instruction.
<?php
$mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT columnName from tablename")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
EDIT:
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
Try simple query like:
SELECT COUNT(*) AS count
FROM mytable
If you dont want to use COUNT in SQL, you can just select all rows (SELECT id FROM table) and then just use PHP count().
also you simply do this
"SELECT COUNT(*) AS `Rows`, `any column` FROM `tablename` GROUP BY `any column` ORDER BY `any column` "
mysqli_num_rows should do the trick if you want to count the rows in php.

MySQL in PHP gives error, MySQL in phpmyadmin does not

I want to truncate a table via PHP. It has some foreign keys, so I use the little trick where I set my foreign key check to zero:
$query_truncate_extension = "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE extension; SET FOREIGN_KEY_CHECKS = 1;";
When I execute the script, the mysqli_error() gives me the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TRUNCATE TABLE extension; SET FOREIGN_KEY_CHECKS = 1' at line 1
So my table doesn't get truncated at all. But the weird thing is when I put this exact same query in the SQL-query section in phpmyadmin, it doesn't throw an error at all and my table is empty afterwards.
So my question is: why does this code gives an error in PHP, but not in phpmyadmin and how do I solve this?
Thanks in advance!
If you wan to run multiple queries in one call then you need to use
mysqli_multi_query()
This is a function allows to run one or multiple queries which are concatenated by a semicolon.
To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().
You can read more detail here.
http://php.net/manual/en/mysqli.multi-query.php
--------- Example Program at the link above -------------
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
You can change it according to your requirement.
Use single query in single call like
$query_truncate_extension = "SET FOREIGN_KEY_CHECKS = 0"

PHP SQL Temporary table won't work

I'm trying to understand how the temporary tables work. But even when I copy and paste it from my tutorials, I don't get the expected result.
See the code underneath for more info.
At the moment the .php file returns a blank page (no errors),
while i would expect it to be:
1 Row inserted.
I looked for the error code but found out that temporary tables don't have an error code.
Does someone know what I'm doing wrong?
<?php
$link = mysqli_connect("localhost","xxx","xxx","xxx");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TEMPORARY TABLE myCity (Name CHAR(30)");
$city = "'s Hertogenbosch";
$city = mysqli_real_escape_string($link, $city);
/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT INTO myCity (Name) VALUES ('$city')"))
{
printf("%d Row inserted.\n", mysqli_affected_rows($link));
}
mysqli_close($link);
?>
Looks like you have an error in your sql creation. You are missing a closing parenthesis: ")"
CREATE TEMPORARY TABLE myCity (Name CHAR(30)
Adrien.
this works for me
<?php
ini_set("display_errors",1);
error_reporting(E_ALL);
$mysqli = new mysqli("localhost", "root", "admin123", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TEMPORARY TABLE CITIES (
id int(11) NOT NULL,
name varchar(64) NOT NULL
)");
//$mysqli->autocommit(FALSE);
$mysqli->query("INSERT INTO CITIES VALUES ('1', 'Bavaria')");
$mysqli->query("INSERT INTO CITIES VALUES ('2', 'Havana')");
//$mysqli->commit();
if ($result = $mysqli->query("SELECT * FROM CITIES LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
//$mysqli->query("DROP TABLE CITIES");
$mysqli->close();
Remember Temporary tables only exist by session, sometimes we need create conventional table and truncate later...
You would must think use DB lib like Doctrine DBAL or ADODb or something like that...

search recent in mysql?

I have a table named 'transactions', in which i store a user's all transactions. i want an mysql query such that it would extract recent 3 transactions from table for a specific user id.
i know i can use limit.
SELECT * FROM 'transactions' WHERE 'userid'=20 LIMIT 0,3;
but how can i access attributes of different transactions which are returned as object after query? also using limit 0,3 would start search from start of table but i want to start search from bottom of table. I am using it with php.
Well, since you are not using a programming language, and just mysql, all your attributes would be displayed in the query result in the console window.
Edit:
To access your query and results, see the following article on PHP.net's website: http://www.php.net/manual/en/mysqli-result.fetch-assoc.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
/EndEdit
To sort newest first, assuming you have a id column, use ORDER BY:
SELECT * FROM 'transactions' WHERE 'userid'=20 ORDER BY id DESC LIMIT 0,3;

Return variable from stored procedure MySQL

How can I return a declared string like ( lastInsertId ) from my MySQL stored procedure and out? It's really annoying I can't return error messegts, complate messages and more out to my code in PHP5.
I hope somebody can help me here, I have search Google around without luck :(
Thanks to everybody.
The function you need is mysqli->insert_id
This is the example that php.net provides, I think this function is what you are looking for:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
You'll find more info here: php.net: mysqli->inert_id - Manual
If you need more help using it I'll be happy to help you.

Categories