I have the following code and I'm getting crazy with calling an auto_increment id
$sql = "INSERT INTO tablename (x1, x2) VALUES(?,?)";
if($query = $db->prepare($sql)){
$query->bind_param('ss', $x1, $x2);
$query->execute();
$id = mysqli_insert_id($query);
For a reason I don't know why this is not working. I also tried
$id = mysqli_insert_id($sql);
And
$id = mysqli_insert_id();
I just decided to work with mysqli. Before that, I only used MySQL where I had no problem with
$id = mysql_insert_id();
You must pass the mysqli link to mysqli_insert_id(), not the query:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$sql = "INSERT INTO tablename (x1, x2) VALUES(?,?)"
$result = mysqli_query($link, $sql);
$id = mysqli_insert_id($link);
or since you were using object oriented style:
// ...
$id = $mysqli->insert_id;
Probably something like
$query->commit(); OR $query->close();
It's best to stick to OOP style. It will cause you less confusion. In OOP style you only need to access a property on the object. For example:
$stmt = $db->prepare($sql);
$stmt->bind_param('ss', $x1, $x2);
$stmt->execute();
// Either one will work
$stmt->insert_id;
$db->insert_id;
If you want to use the procedural mysqli style then you have to remember that there are two functions. One if for the mysqli object and the other is for mysqli_stmt object. You need to pick either one of them, but you have to pass the right object to it.
// For mysqli_stmt object
mysqli_stmt_insert_id($stmt);
// For mysqli object
mysqli_insert_id($db);
$result = mysql_query($sql);
if(!$result) {
{
die('Error: ' . mysql_error());
} else {
echo "<p>Done!.</p>";
}
Try this and check the output...
Related
I'm not sure where I'm going wrong here. I've searched similar issues on here with no luck. Any help would be greatly appreciated. Thanks!
$check = "SELECT Number FROM advisors";
$result = mysqli_query($check);
$count = mysqi_num_rows($result);
echo $count;
You should use php prepare statement like this
$count = 0;
$mysqli = new mysqli(host, dbUser, dbPassword, dbName);
mysqli_set_charset($mysqli, "utf8");
$sql = "select count(*) from advisors";
if ($stmt = mysqli_prepare($mysqli, $sql))
{
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $c);
if (mysqli_stmt_fetch($stmt))
{
$count = $c;
}
mysqli_stmt_close($stmt);
}
return $count;
For more information, here is the link for php prepare statement
Documentation of php prepare statement
You should use COUNT in query and see if it works,
"SELECT COUNT (number) as number FROM advisors";
By the way, I noticed a typo in $count, it should be $count = mysqli_num_count($result).
I was using the following code to execute the queries in the database:
$sql = "SELECT * FROM cc_topchoices WHERE location='$location' ORDER BY position asc";
$result = mysqli_query($conn, $sql);
I have read that this way to make the queries is not secure so I want to use the statements prepare() and execute() in php
Now my code looks like this:
$sql = "SELECT * FROM cc_topchoices WHERE location=:location ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->execute(array(":location" => $location));
$result = mysqli_query($conn, $stmt);
But this give me this error:
Fatal error: Call to a member function execute() on boolean
Any idea?
EDIT
Now my code looks like this:
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "$username", "$password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8"); //BECAUSE I NEED TO WORK WITH CHINESE LANGUAGE
$sql = "SELECT * FROM cc_topchoices WHERE location=? ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':location', $location);
$stmt->execute(array($location));
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
if ($result > 0) {
// output data of each row
while($row = $stmt->fetch()) {
echo "<li><div><a href='". $row["rest_url"] ."'><img src='images/top_choices/". $row["image"] ."' alt='". $row["alt_desc"]. "' /></a></div></li>";
}
} else {
echo "0 results";
}
is working :) just need to know if this is a good and secure practice
PDO supports named parameters. MySQLi does not. $stmt is false to show you that the SQL you tried to prepare is syntactically malformed. Use ? instead of :location. Check the MySQLi manual for the correct way to use MySQLi. Or, alternately, switch to PDO.
Use below code to fetch records instead of mysqli_query when using pdo statements if your query returns single row.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result['db_column'];
And if return multiple rows:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($result = $stmt->fetch()) {
echo $result['db_column'];
}
And one more thing, always put your prepared statement in try{}..catch{} block.
It will work for you.
want i want is to query my db with post variable in the query. It's not really working for me, does anyone know how to do it properly?
Here is what i have so far.
$query = "SELECT column FROM `table` WHERE 'name' = '$_POST[checkname]'";
$result = mysqli_query($db, $query) or die ("no query");
$cod = mysqli_fetch($result);
echo $cod;
Any help is appreciated. Thanks guys.
Mysqli supports prepared statements, which protect against sql injection attacks. It would look like this:
/* Create a prepared statement */
$stmt = $mysqli -> prepare("SELECT column FROM table WHERE name=?");
/* Bind parameters */
$stmt -> bind_param("s", $_POST['checkname']);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
echo $result;
Check the manual for more info.
A quick rundown, in response to the comment:
In $stmt->prepare("..."), you're forming your query, and you hold the place of any variables you intend to use with a "?"
In $stmt -> bind_param(...), you're binding the variables to their corresponding question mark. The first argument is the type, the following arguments are the variables. If you were using a string and an integer, inside the parenthesis it would look like "si", $stringVar, $intVar
In $stmt -> bind_result(...) you are stating what you are binding the results to. If the query was for a name and age, inside the parethesis would look like $name, age
In $stmt->fetch(), you're fetching the result. If it was multiple rows returned, you would do something like:
while($stmt->fetch()) {
//code here
}
Alternatively, you could use PDO. It would look something like this:
/* Create a prepared statement */
$stmt = $pdo->prepare("SELECT column FROM table WHERE name=:checkname");
/* Bind parameters */
$stmt->bindParam(':checkname', $_POST['checkname']);
/* Execute it */
$stmt->execute();
/* Fetch results */
$obj = $stmt->fetchObject();
echo $obj->column;
Check the manual for more info.
//it is apsulutly
// work
if(isset($_POST['checkname']))
{
$post = mysql_real_escape_string(trim($_POST[' checkname ']));
$query = "SELECT column FROM `table` WHERE name = '$post'";
$result = mysqli_query($db, $query) or die ("no query");
$cod = mysqli_fetch_all($result);
echo implode($cod[0]);
echo implode($cod[1]);//For particular cell
}
it works, just try it out like this
following your code...
if(isset($_POST['checkname']))
{
//to avoid SQL injections
$post = mysql_real_escape_string(trim($_POST['checkname']));
$query = "SELECT column FROM `table` WHERE name = '$post'";``
$result = mysqli_query($db, $query) or die ("no query");
$cod = mysqli_fetch($result);
echo $cod;
}
Could somebody please point me in the right direction. I am in the process of making the transition from MySql to MySqli. Normally I would select from the database using th code below and it would allow me to easily use the column value as a working variable:
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = mysql_query($SQLCommand);
$DataRow = mysql_fetch_assoc($Data);
$var1 = $DataRow["column1"];
$var2 = $DataRow["column2"];
$var3 = $DataRow["column3"];
$var4 = $DataRow["column4"];
I have researched how to do the MySql equivalent but I find theres a lot of different way using loops etc. Is there a like for like (for want of a better description) that does the same thing? Thanks in advance.
Instead of going with the flow, i care to suggest a PDO alternative
$db = new PDO($dsn, 'username','password');
//$dsn is the connection string to your database.
//See documentation for examples
//The next two rows are optional, but i personally suggest them to
//ease developing, debugging (the 1st) and fetching results (the 2nd)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$stmt = $db->prepare("SELECT * FROM table WHERE column1 = :c1");
$stmt->bindValue(':c1', 'ok'); //This example is trivial and not necessary
//but it gains relevance when the bound value
//is a variable
$rows = $stmt->fetchAll(); //if you expect a single row use fetch() instead
//do something with the results
You can read more about PDO here: PDO manual
The biggest PDO advantage is that it's independent of the actual database in use by your application. If, by chance, you want to change database in the future, for example SQLITE or PostgreSQL, the only* change you have to make is your $dsn connection string
[*] True only if you used standard SQL queries and nothing vendor-specific.
A direct conversion would be:
$Data = mysqli_query($connection, $SQLCommand);
$DataRow = mysqli_fetch_assoc($Data);
The difference, other than the i is that mysqli_query requires the connection as an argument (as do most mysqli_* functions).
MySQLi also has an object oriented style:
$Data = $connection->query($SQLCommand); // assuming you created the $connection object
$DataRow = $data->fetch_assoc();
They should be like
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
$SQLCommand = "SELECT * FROM table WHERE column1 = 'ok'";
$Data = $mysqli->query($SQLCommand);
$DataRow = $mysqli->fetch_assoc($Data);
Try this LINK
My suggestion is to use mysqli prepared statement whenever you are using user inputs to prevent SQL injection:
See below code uses object oriented approach and prepared statement
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") ||
!$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))") ||
!$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = ?");
/* Prepared statement, stage 2: bind and execute */
$id = 1;
//note below "i" is for integer, "s" can be used for string
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));
?>
Can I do a WHERE clause inside an IF statement?
Like I want something like this:
$SQL = mysql_query("SELECT * FROM `table` ORDER BY `row` DESC");
$rows = mysql_fetch_array($SQL);
$email = $_SESSION['email_of_user'];
if($rows["row"] == "1" WHERE `row`='$email' : ?> (Pulls the logged in user's email)
Edit Server
<?php else : ?>
Add Server
<?php endif; ?>
Do I need (" where the WHERE statement is? Because I tried that and it didn't seem to work...
Or can I do it with an if condition inside of a where clause? Not sure of all these terms yet so correct me if I'm wrong...
You cannot mix up a query statement with PHP's statement. Instead write a query extracting desired results and check if there are any rows from that query.
I will show you an example:
$query = "SELECT * FROM `TABLE_NAME` WHERE `field` = '1' && `email`='$email'"; //Create similar query
$result = mysqli_query($query, $link); //Query the server
if(mysqli_num_rows($result)) { //Check if there are rows
$authenticated = true; //if there is, set a boolean variable to denote the authentication
}
//Then do what you want
if($authenticated) {
echo "Edit Server";
} else {
echo "Add Server";
}
Since Aaron has shown such a effort to encourage safe code in my example. Here is how you can do this securely. PDO Library provides options to bind params to the query statement in the safe way. So, here is how to do it.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Create the connection
//Create the Query Statemetn
$sth = $dbh->prepare('SELECT * FROM `TABLE_NAME` WHERE field = :field AND email = :email');
//Binds Parameters in the safe way
$sth -> bindParam(':field', 1, PDO::PARAM_INT);
$sth -> bindParam(':email', $email, PDO::PARAM_STRING);
//Then Execute the statement
$sth->execute();
$result = $sth->fetchAll(); //This returns the result set as an associative array