How to get affected rows using mysqli? - php

I create function for make query in database:
function mysqli($query){
$mysqli = new mysqli('test','test','test','test');
if (mysqli_connect_errno()) {
printf("Bad connect: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query("SET NAMES utf8");
$result = $mysqli->query("set character_set_client='utf8'");
$result = $mysqli->query("set collation_connection='utf8_general_ci'");
$result = $mysqli->query($query);
$mysqli->close();
return $result;
};
In next step I want get count affected rows.
For this I make:
$res2 = mysqli("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
echo $res2->affected_rows;
But I get Notice: Trying to get property of non-object on line echo $res2->affected_rows;
How to get count of affected_rows?

This function is pointless and harmful.
And should never be used.
All other answer told you to remove most useless parts. While what you really have to remove is connection part. Which makes whole function useless.
And even harmful, as you will kill your MySQL server by connecting every time you are going to run a query.
And even more harmful as it doesn't support prepared statements.

Remove $mysqli->close(); And make use of
$mysqli->query("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
echo $mysqli->affected_rows;

change
$res2 = mysqli("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
to
$res2 = mysqli_query("INSERT INTO Table (name, value) VALUES ('$name', '$value')");

Remove the line:
$mysqli->close();
from the function. and this will work.
function mysqli($query){
$mysqli = new mysqli('test','test','test','test');
if (mysqli_connect_errno()) {
printf("Bad connect: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query("SET NAMES utf8");
$result = $mysqli->query("set character_set_client='utf8'");
$result = $mysqli->query("set collation_connection='utf8_general_ci'");
$result = $mysqli->query($query);
$arr = array($result,$mysqli);
return $arr;
}
Amd the use like this:
$res2 = mysqli("INSERT INTO Table (name, value) VALUES ('$name', '$value')");
echo $res2[1]->affected_rows;
And your result will be in this variable: res2[0];
Read this answer: mysqli_affected_rows() expects parameter 1 to be mysqli, object given

Related

get values from select query and put them into variables

I'm a beginner in php and mysql, I just want to know how can I put values that I got from a select query into variables.
For example I used this mysql query :
$req="SELECT type, titre, auteur, abstract, keywords FROM manusrit WHERE file='$name';";
$req1=mysql_query($req);
I want to put the value of the column type in $type variable and the value of auteur in a variable called $auteur and the same for abstract, and keywords.
How can I do this?
FIRST of all use PDO instead of mysqli.
Example :
$link = mysql_pconnect($hostname, $username, $password) or die('Could not connect');
//echo 'Connected successfully';
mysql_select_db($dbname, $link);
$name = $_POST['Name'];
$query ="SELECT type, titre, auteur, abstract, keywords FROM manusrit WHERE file='$name';";
mysql_query("SET NAMES 'utf8'", $link);
$result = mysql_query($query, $link);
//Now You FETCH result and read one by one
while ($row = mysql_fetch_assoc($result)) {
//Access COLMN like this
print $row['abstract'];
print $row['keywords'];
}

verifying and inserting details into db

I need to insert the details (name, id , number )of many documents into database if they are not already existing and if they exist i just need to do a update for any changed information. I have arrived at the following code but it doesn't work. I am new to this and need help on this.
foreach($A->Documents -> Document as $Document)
{
$query = "SELECT * from table where id = '".$Document->id."'";
$outcome = mysql_query($query) or die(mysql_error());
if(($outcome)&&(mysql_num_rows($result)>0)){
echo "Document already available" ;
while($row = mysql_fetch_object($outcome)){
if(!($outcome->name == $document->name)){
$update= "UPDATE table SET name= '.$Document->Name.'";
mysql_query($update) or die(mysql_error());
}
else
{
$insert= "INSERT table SET name= '.$Document->Name.'";
mysql_query($update) or die(mysql_error());
}
}
}
}
Use $row->name instead of $outcome->name. and your INSERT statement is wrong.
while($row = mysql_fetch_object($outcome)){
if(!($row->name == $document->name)){
$update = "UPDATE table SET name ='".$Document->Name."' WHERE id = ".$Document->id;
mysql_query($update) or die(mysql_error());
}
else {
$insert = "INSERT INTO table (name) VALUES('".$Document->Name."')";
mysql_query($insert) or die(mysql_error()); // $insert not $update
}
}
Note: Stop using mysql_* functions! Use PDO or mysqli_* instead. And use prepared statements
Change the
mysql_query($update) or die(mysql_error());
To:
$insert = INSERT into table_name values(" values");
mysql_query($insert) or die(mysql_error());
in the else condition
Issue is with $result variable with in if statement
( if(($outcome)&&(mysql_num_rows($result)>0)){)
It should be $outcome because you initialized query output to $outcome variable
First of, dont yse mysql_ functions. Read the docs (read the warning).
use mysqli or PDO instead.
Then, your INSERT statement is wrong.
INSERT INTO table (col1) VALUES (value_for_col1);

Can't insert into to my Database with PHP

I want to insert some info into a table but it doesn't works. This is the code.
<?php
$con=mysql_connect("localhost","Chew","*****","Birthdays");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Name="Something";
$Desc="Something";
$Lang="En";
$D="1";
$M="1";
echo "<br>";
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, Day, Month) VALUES ('".$Name."', '".$Desc."', '".$Lang."', '".$D."', '".$M."' );";
$qr= mysql_query($con, $sql) or die("Error: " . mysql_error());
mysql_close($con);
?>
MONTH and DAY are names of MySQL functions. If you are going to name columns with those names you must escape them with ticks:
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, `Day`, `Month`) VALUES ('".$Name."', '".$Desc."', '".$Lang."', '".$D."', '".$M."' );";
read mysql_query
$qr= mysql_query($sql, $con) or die("Error: " . mysql_error());
NB: mysql_* is deprecated, use mysqli_* or pdo
If D and M are numbers, your SQL should not use quotes (') in the VALUES-part of your SQL
You should be using Object Oriented mechanism for doing connection with MySQL with the help of MySQLi class
example
// The var's in complete caps means they might be defined as constant variable
// DB_HOST - database hostname
// DB_USER - database user
// DB_PASS - database password
// DB_NAME - database instance name
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($db -> connect_error){
// in case there are errors
die("Connect Error (" . $db -> connect_errno . ") " . $db -> connect_error);
}
$Name= mysql_real_escape_string("Something"); // helps to escape special characters like quotes
$Desc= mysql_real_escape_string("Something");
$Lang="En";
$D="1";
$M="1";
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, `Day`, `Month`) VALUES ('".$Name."', '".$Desc."', '".$Lang."', $D, $M );";
$db -> query($sql) or die("Error: " . $db -> error_msg);
echo "Insert id: " . $db -> insert_id;
EDIT: Code to fetch data from database
C_Chewbacc,
I would recommend you on reading more on PHP-MySQL connection using Object Oriented mechanism
http://in2.php.net/mysqli
Try this code below
$sql = "SELECT * FROM Birthdays";
$result = $db -> query($sql); // SELECT query returns result object here
// We iterate over this result object and fetch each row on every iteration
// When the resultant object has nothing to return, NULL is initialised in $row
// When $row = NULL becomes the exit point of WHILE loop
while($row = $db -> fetch_array($result)){
var_dump($row); // This will display every row of data
}

PHP MySql Update else Insert Error "Warning: mysql_result()"

I'm trying to go threw my table nonbulkmdu and look into r10database to find if there is a duplicate, if there is it will update 4 fields if its not it will insert a new row. I keep getting the error
Warning: mysql_result(): supplied argument is not a valid MySQL result resource in on line 19-23.
What am I doing wrong?
<?php
$username="";
$password="";
$database="";
$link = mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM nonbulkmdu";
if ($result=mysql_query($query, $link)) {
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$address=strtoupper(mysql_result($result,$i,"address"));
$drops=mysql_result($result,$i,"drops");
$city=mysql_result($result,$i,"city");
$citycode=mysql_result($result,$i,"citycode");
$feature_type=mysql_result($result,$i,"Feature_Type");
$result = mysql_query("update r10_database
set drops=$drops, citycode=$citycode, city=$city, Feature_Type=$feature_type
where address=$address;");
if (mysql_affected_rows()==0) {
$result = mysql_query("insert into r10_database (address,
drops,
city,
citycode,
Feature_Type)
values ($address,
$drops,
$city,
$citycode,
$Feature_Type);");
}
$i++;
}
} else {
echo mysql_error();
}
mysql_close();
?>
You're missing quotes around the values in the UPDATE and INSERT call:
$result = mysql_query("update r10_database
set drops='$drops', citycode='$citycode', city='$city', Feature_Type='$feature_type'
where address='$address';");
if (mysql_affected_rows()==0) {
$result = mysql_query("insert into r10_database (address,
drops,
city,
citycode,
Feature_Type)
values ('$address',
'$drops',
'$city',
'$citycode',
'$Feature_Type');")
BTW, if address has a unique key in the table, you can do both queries at once, using INSERT ... ON DUPLICATE KEY UPDATE.

I can add a string literal to my table but if I pass a string as a variable it only works with numbers

I have a simple mysql table
This is the code to connect to database and insert into testtable:
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$sql = "INSERT INTO testtable
VALUES (NULL, $forename)";
$res = mysqli_query($mysqli, $sql);
if($res === TRUE) {
echo "data successfully inserted.";
} else {
printf("Could not insert data: %s\n", mysqli_error($mysqli));
}
mysqli_close($mysqli);
}
In this case I try to insert $forename into my table. If I use a string literal like 'Jim' or '123' it gets inserted. If $forename is given the value 123 or any other number it gets inserted. If $forename = 'Jim' I get an error telling me there is no column 'Jim' as though I were specifying a column in the table.
It has happened to me before, you are missing quotes in the query. Try:
$sql = "INSERT INTO testtable VALUES ('{$forename}')";
When forename is 'Jim', the query expands to ".... VALUES(NULL, Jim)", but you want "... VALUES(NULL, 'Jim')". Your query should read "...VALUES(NULL, 'Jim')".
use a prepared statement
$db= mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$sql = "INSERT INTO testtable (testfield) VALUES (?)";
if ($statement =$db->prepare($sql)){
$statement->bind_param("s",$forename);
msqi_stmt_execute($statement);
};
Since your id field is an autonumber, you don't need to insert anything. You should also really get in the habit of specifying the columns to insert into:
Instead of :
INSERT INTO testtable VALUES (NULL, $forename)
use:
INSERT INTO testtable
(
`testfield`
)
VALUES
(
'$forename'
)
Note that the "quotes" around the field name are back-ticks, not single quotes.
Of course, using string insertion like this is a security risk, so you really should be using prepared statements, as case1352 demonstrates in his answer.

Categories