# variable in mysqli statement - php

I'm now sitting for hours and trying to pass multiple queries through my PHP script.
Basically, I'd like to query for the last inserted index in the address folder, then save the index as a variable "#address", so that I can use it in the next query, etc.
The SQL script works fine, however, as soon as I use it in my PHP script, it doesn't insert any new data.
Also I don't want to split it into multiple single queries, because this script will be used in a web application, where a lot of new registrations will be processed and therefore it is important, that when two customer register at the same time, it is ensured that the foreign keys will be assigned in the right way.
Any suggestions are appreciated.
<?php
$link = mysqli_connect("localhost", "root", "test", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'SET #address = (select max(idaddress) from test.address) + 1; SET #customer= (select max(idcustomer) from test.customer) + 1;
SET #contract= (select max(idcontact) from test.contract) + 1;
INSERT INTO `test`.`address` (`idaddress`, `street`, `number`, `zip`) VALUES (#address, "main street", "584", "54545");
INSERT INTO `test`.`customer` (`idcustomer`, `name`, `surname`, `customeraddress`) VALUES (#customer, "Smith", "Michael", #address);
INSERT INTO `test`.`contract` (`idcontract`, `customernumber`) VALUES (#contract, #costumer);
';
echo $query; // for testing purposes
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}
mysqli_close($link);
?>
c0mplexity

Use this instead of yours.Hope it will work for you.
$query = "SET #address = (select max(idaddress) from test.address) + 1";
$query = "SET #customer= (select max(idcustomer) from test.customer) + 1";
$query = "SET #contract= (select max(idcontact) from test.contract) + 1";
$query = "INSERT INTO `test`.`address` (`idaddress`, `street`, `number`, `zip`) VALUES (#address, 'main street', "584", "54545")";
$query = "INSERT INTO `test`.`customer` (`idcustomer`, `name`, `surname`, `customeraddress`) VALUES (#customer, 'Smith', 'Michael', #address)";
$query = "INSERT INTO `test`.`contract` (`idcontract`, `customernumber`) VALUES (#contract, #costumer)";

Related

How to Insert returned values in another table

I am selecting 5 rows at random from a table.
$query = "SELECT stdid, name FROM students order by rand(UNIX_TIMESTAMP()) limit 5"
$myquery = mysqli_query($db_connect, $query);
while($students = mysqli_fetch_assoc($myquery)){
$stdid =$students['stdid']; $name = $students['name']; $dept = $students['dept'];
echo "<br><br>".$stdid."<br>".$name."<br>".$dept;
//NOT SURE IF I ADD INSERT HERE
}
I want to INSERT (5 rows) the displayed 'stdid' into another table.
Do i need to add the INSERT in the WHILE loop ? Is there another way to go about this ?
Many thanks.
Using PHP MySQLi prepared statements to prepare the insert query, once, outside the loop, then reuse that prep'd insert object to dump values into the desired table inside the loop:
$query1 = "SELECT stdid, name FROM students order by rand(UNIX_TIMESTAMP()) limit 5";
$myquery1 = mysqli_query($db_connect, $query1);
// prepare insert stdid
$query2 = "INSERT INTO someothertable (stdid) VALUES (?)";
$myquery2 = mysqli_prepare($db_connect, $query2);
mysqli_stmt_bind_param($myquery2, 'i', $stdid);
while($students = mysqli_fetch_assoc($myquery1)){
$stdid =$students['stdid']; $name = $students['name']; $dept = $students['dept'];
echo "<br><br>".$stdid."<br>".$name."<br>".$dept;
// insert stdid
mysqli_execute($myquery2);
}
It will work to put the insert inside the while loop. With only five entries, this won't be too inefficient. If you want to insert all of the values at once, you should check out this question on how to do it.
Inserting multiple rows in a single SQL query?
You can just insert the statement as mentioned above. Here is some code to help you make a prepared statement which will add your values that are not predefined.
$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");
/* Prepare an insert statement */
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
/* Execute the statement */
$stmt->execute();
$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';
/* Execute the statement */
$stmt->execute();
/* close statement */
$stmt->close();
Taken from the manual. Hope it helps!

Adding multiple fields to DB using PHP

I am currently using the following function:
if(isset($_REQUEST["function"]) && ($_REQUEST["function"] == "setnm")){
$value = $_REQUEST["value"]; //field to edit
$con=mysqli_connect("localhost", "root", "", "hike_buddy");
//Check Connection
if(mysqli_connect_errno())
{
echo "failed to connect:".mysqli_connect_error();
}
mysqli_query($con, "INSERT INTO user_com (name) VALUES ('$value')");
mysqli_close($con);
}
How can I alter this code so it will change the value of two fields?
For instance I have a comment and a name column and I want to update them both (different values) with one function.
Never use un-escaped strings specified by the user in your database queries.
So, if you're using mysqli:
$value1 = $con->real_escape_string($_REQUEST['value_1']);
$value2 = $con->real_escape_string($_REQUEST['value_2']);
$query = "INSERT INTO my_table (column_1, column_2) VALUES ('$value1', '$value2')";
$con->query($query);
Are you trying to INSERT new data in the database or UPDATE existing data?
If you want to update data, you should use the UPDATE statement:
$query = "UPDATE my_table SET column_1 = '$value1', column_2 = '$value2' WHERE my_table_key = '$key'";
Also, you need to escape these variables like har-wradim suggested.
You can do the following:
if(isset($_REQUEST["function"]) && ($_REQUEST["function"] == "setnm")){
$value = $_REQUEST["value"]; //field to edit
$comment = $_REQUEST["comment"]; //This is your comment
$con=mysqli_connect("localhost", "root", "", "hike_buddy");
//Check Connection
if(mysqli_connect_errno())
{
echo "failed to connect:".mysqli_connect_error();
}
//Edit the query like so to update insert the comment along with the name.
mysqli_query($con, "INSERT INTO user_com (name, comment) VALUES ('$value', '$comment')");
mysqli_close($con);
}

Find a value in a table row, and if it is there, update it

I'm trying to find a person in my table and update their score. This is the code I have right now. For some reason it's not working. Instead of changing the person's score, it will just make a new row with the same name of the person.
$name = $_POST["strtolower(name)"];
$team = $_POST["team"];
$num = $_POST["number"];
$goals = $_POST["goals"];
if($query = mysqli_query("SELECT goals FROM goalscorers WHERE name=$name ", $db)){
while($row = mysqli_fetch_assoc($query)){
$origgoals = $row['goals'];
$newgoals = (int)$origgoals + (int)$goals;
mysqli_query($db, "UPDATE goalscorers SET goals=$newgoals WHERE name=$name ");
echo "<h1>Thank you for submitting your details! <br /> Add another</h1>";
}
mysqli_free_result($query);
}
else {
$query = "INSERT INTO goalscorers (name, team, num, goals) VALUES ('$name','$team','$num','$goals') ";
$result = mysqli_query($query, $db);
if (mysqli_error()) { print "Database ERROR: " . mysql_error(); }
echo "<h1>Thank you for submitting your details! <br /> Add another</h1>";
}
I'm very new to both PHP and MySQL so it's probably a basic mistake.
Also, I already am connected to the database.
Your immediate problem is that you don't have quotes around string values in your sql queries. Change
"SELECT goals FROM goalscorers WHERE name=$name "
to
"SELECT goals FROM goalscorers WHERE name = '$name'"
^ ^
and
"UPDATE goalscorers SET goals=$newgoals WHERE name=$name "
to
"UPDATE goalscorers SET goals=$newgoals WHERE name = '$name'"
^ ^
On a side note: learn and use prepared statements. Your code is vulnerable to sql injections.
UPDATE1: You can drastically simplify your code with INSERT ... ON DUPLICATE KEY UPDATE. In order for it to work properly you have to have a UNIQUE (PRIMARY KEY) index on name column.
Your insert statement then should look like
INSERT INTO goalscorers (`name`, `team`, `num`, `goals`)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE goals = goals + VALUES(goals)
Here is SQLFiddle demo
UPDATE2: Now your code with INSERT ... ON DUPLICATE KEY UPDATE and prepared statement can look like this
$name = $_POST['name'];
$team = $_POST['team'];
$num = $_POST['number'];
$goals = $_POST['goals'];
/* connect to the database*/
$db = new mysqli('localhost', 'user', 'userpwd', 'test');
/* check connection */
if ($db->connect_errno) {
die('Connection failed: ' .$db->connect_error);
}
$sql = 'INSERT INTO goalscorers (`name`, `team`, `num`, `goals`)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE goals = goals + VALUES(goals)';
/* create a prepared statement */
if ($stmt = $db->prepare($sql)) {
/* bind parameters for markers */
$stmt->bind_param("ssii", $name, $team, $num, $goals);
/* execute query */
if ($stmt->execute()) {
echo '<h1>Thank you for submitting your details! <br /> Add another</h1>';
} else {
die('Insert failed: ' .$db->error);
}
/* close statement */
$stmt->close();
} else {
die('Statement prepare failed: ' .$db->error);
}

INSERTING values from one table into another table

I have this code to select all the fields from the 'jobseeker' table and with it it's supposed to update the 'user' table by setting the userType to 'admin' where the userID = $userID (this userID is of a user in my database). The statement is then supposed to INSERT these values form the 'jobseeker' table into the 'admin' table and then delete that user from the 'jobseeker table. The sql tables are fine and my statements are changing the userType to admin and taking the user from the 'jobseeker' table...however, when I go into the database (via phpmyadmin) the admin has been added by none of the details have. Please can anyone shed any light onto this to why the $userData is not passing the user's details from 'jobseeker' table and inserting them into 'admin' table?
Here is the code:
<?php
include ('../database_conn.php');
$userID = $_GET['userID'];
$query = "SELECT * FROM jobseeker WHERE userID = '$userID'";
$result = mysql_query($query);
$userData = mysql_fetch_array ($result, MYSQL_ASSOC);
$forename = $userData ['forename'];
$surname = $userData ['surname'];
$salt = $userData ['salt'];
$password = $userData ['password'];
$profilePicture = $userData ['profilePicture'];
$sQuery = "UPDATE user SET userType = 'admin' WHERE userID = '$userID'";
$rQuery = "INSERT INTO admin (userID, forename, surname, salt, password, profilePicture) VALUES ('$userID', '$forename', '$surname', '$salt', '$password', '$profilePicture')";
$pQuery = "DELETE FROM jobseeker WHERE userID = '$userID'";
mysql_query($sQuery) or die (mysql_error());
$queryresult = mysql_query($sQuery) or die(mysql_error());
mysql_query($rQuery) or die (mysql_error());
$queryresult = mysql_query($rQuery) or die(mysql_error());
mysql_query($pQuery) or die (mysql_error());
$queryresult = mysql_query($pQuery) or die(mysql_error());
mysql_close($conn);
header ('location: http://www.numyspace.co.uk/~unn_v002018/webCaseProject/index.php');
?>
Firstly, never use SELECT * in some code: it will bite you (or whoever has to maintain this application) if the table structure changes (never say never).
You could consider using an INSERT that takes its values from a SELECT directly:
"INSERT INTO admin(userID, forename, ..., `password`, ...)
SELECT userID, forename, ..., `password`, ...
FROM jobseeker WHERE userID = ..."
You don't have to go via PHP to do this.
(Apologies for using an example above that relied on mysql_real_escape_string in an earlier version of this answer. Using mysql_real_escape_string is not a good idea, although it's probably marginally better than putting the parameter directly into the query string.)
I'm not sure which MySQL engine you're using, but your should consider doing those statements within a single transaction too (you would need InnoDB instead of MyISAM).
In addition, I would suggest using mysqli and prepared statements to be able to bind parameters: this is a much cleaner way not to have to escape the input values (so as to avoid SQL injection attacks).
EDIT 2:
(You might want to turn off the magic quotes if they're on.)
$userID = $_GET['userID'];
// Put the right connection parameters
$mysqli = new mysqli("localhost", "user", "password", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Use InnoDB for your MySQL DB for this, not MyISAM.
$mysqli->autocommit(FALSE);
$query = "INSERT INTO admin(`userID`, `forename`, `surname`, `salt`, `password`, `profilePicture`)"
." SELECT `userID`, `forename`, `surname`, `salt`, `password`, `profilePicture` "
." FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "UPDATE user SET userType = 'admin' WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "DELETE FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$mysqli->commit();
$mysqli->close();
EDIT 3: I hadn't realised your userID was an int (but that's probably what it is since you've said it's auto-incremented in a comment): cast it to an int and/or don't use it as a string (i.e. with quotes) in WHERE userID = '$userID' (but again, don't ever insert your variable directly in a query, whether read from the DB or a request parameter).
There's nothing obviously wrong with your code (apart from it being insecure with using non-escaped values directly from $_GET).
I'd suggest you try the following in order to debug:
var_dump $userData to check that the values are as you expect
var_dump $rQuery and copy and paste it into phpMyAdmin to see if your query is not as you expect
If you don't find your problem then please post back your findings along with the structure of the tables you're dealing with

php mysql query not executing correctly

I have a weird problem with my sql script.
I have a string
$query = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message)
VALUES ('93361357', '2162', '27761144734', 'Hoekom');";
But when I execute that string it inserts it to the table but eventid stays 0, if I run that exact command in cmd it works perfectly?
Any ideas why this is not inserting all the values?
Edit Full code
<?php session_start();
$link = mysql_connect("localhost", "username", "password"); //removed u and p for posting
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db("db", $link) //removed db name for posting
or die ("Couldn't open smss:" . mysql_error());
$id = $_SESSION['id'];
$message = $_REQUEST['promo_message'];
$timeToSend = $_REQUEST['timeToSend'];
$dateToSend = $_REQUEST['dateToSend'];
if(isset($_REQUEST['input_cell']))
{
$receiver = $_REQUEST['input_cell'];
if($receiver != '')
{
$response_string = sendSMSPortalSchedule($message, $receiver, $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
$query1 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message');";
mysql_query($query1);
echo mysql_error();
}
}
if(isset($_REQUEST['single_cell']))
{
$receiver = $_REQUEST['single_cell'];
if($receiver != 'none')
{
$response_string = sendSMSPortalSchedule($message, $receiver, $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
$query2 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message');";
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
mysql_query($query2);
echo mysql_error();
}
}
if(isset($_REQUEST['sento_group']))
{
$array = $_REQUEST['sento_group'];
foreach($array as $receiver)
{
if($receiver != 'none')
{
$query = 'SELECT cell_number FROM cell_groups WHERE group_id ="'.$receiver.'"';
$result2 = mysql_query($query) or die('Fail');
while($row=mysql_fetch_array($result2))
{
$response_string = sendSMSPortalSchedule($message, $row['cell_number'], $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
$to = $row['cell_number'];
$query3 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$to', '$message');";
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
mysql_query($query3);
echo mysql_error();
}
}
}
}
}
This is the table
id = INT
eventid = BIGINT(20)
bus_id = INT
cell_num = VARCHAR
sms_message = VARCHAR
The SQL command itself is correct. The problem must be elsewhere.
Firstly, are you sure that the values of your parameters are correct? Try outputting the query after variable interpolation to see if it is correct:
$query1 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message')";
echo $query1;
Seondly I notice that in you have INSERTs in multiple places. Make sure all of them work as expected. Remember that the one you think is executing may be different from the one that is actually executing.
I found the problem, the service I was using got changed to return XML where it usually just returned an integer, this caused me to try and insert XML into my BIGINT field, which is not possible. So in the end the problem was caused by an updated service that didn't notify clients about changes.

Categories